原文同步发布于我的wiki,查看原文或更新请移步: 点击打开链接
原理
- 不懂了,没深入研究物理引擎。。。但用用还是可以的。
Demo及源码
- 基于cocos 3.4final
- https://github.com/cheyiliu/CollisionDetection
Demo解读
主要代码
- 构建物理世界
auto scene = Scene::createWithPhysics(); scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);//debug模式 Vect gravity = Vect(0.0f,0.0f);//0重力 scene->getPhysicsWorld()->setGravity(gravity);
- 设置物理世界的大小
//定义世界的边界 auto body = PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT,5.0f); auto edgeNode = Node::create(); edgeNode->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2)); edgeNode->setPhysicsBody(body); this->addChild(edgeNode);
- 注册碰撞事件的监听
// 注册物理碰撞事件监听 auto listener = EventListenerPhysicsContact::create(); listener->onContactBegin = [this](PhysicsContact& contact) { return true; }; listener->onContactPreSolve = [] (PhysicsContact& contact,PhysicsContactPreSolve& solve) { // log("onContactPreSolve"); return true; }; listener->onContactPostSolve = [] (PhysicsContact& contact,const PhysicsContactPostSolve& solve) { // log("onContactPostSolve"); }; listener->onContactSeperate = [](PhysicsContact& contact) { log("onContactSeperate"); }; Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority( listener,1);
- 给精灵设置物理body
//设置物理body auto body = PhysicsBody::createBox(sp->getContentSize()); body->setContactTestBitmask(0xFFFFFFFF); sp->setPhysicsBody(body);
- 其他和@R_301_485@cocos2d-x-3.3-019-碰撞检测1-矩形区域是否相交一样,略
优缺点
效果图
- 开了debug模式https://github.com/cheyiliu/All-in-One/raw/master/res/cocos2d/CollisionDetection-way2-use-physics-engine.gif