3.0以后将box2d和chipmunk这两个物理引擎进行了封装,使用起来很的便利
1、创建物理世界场景auto scene = Scene::createWithPhysics(); scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); //调试时使用2、在场景中加入重力Vect gravity = Vect(0.0f, -10.0f); //-10表示重力向下 scene->getPhysicsWorld()->setGravity(gravity);3、创建物理边界,边界有碰撞体auto body = PhysicsBody::createEdgeSegment(Point(0,0),Point(600,0),PHYSICSBODY_MATERIAL_DEFAULT, 3); //3是边线度 auto edgeNode = Node::create(); edgeNode->setPosition(Point(0,10)); edgeNode->setPhysicsBody(body); scene->addChild(edgeNode);
void GameScene::addBoxBodyForSprite(Sprite *sprite){ auto body = PhysicsBody::createCircle(sprite->getContentSize().width / 2); // body->setCategoryBitmask(0); //当为0不仅能闯过并且还检測不到碰撞 body->setContactTestBitmask(1); //有碰撞检測 body_player->setRotationEnable(false); //设置是否旋转 /** 设置body是否受引力影响 */ body->setGravityEnable(true); //是否受重力影响 sprite->setPhysicsBody(body);
5、碰撞监听 在onEnter中绑定监听void GameScene::onEnter() { Layer::onEnter(); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this); //刚開始碰撞,监听 contactListener->onContactPreSolve = CC_CALLBACK_2(GameScene::onContactPreSolve, this); //碰撞中监听 auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); }
6、開始碰撞监听函数bool GameScene::onContactBegin( const PhysicsContact& contact){ auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode(); auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode(); return true; //返回true,才干够继续监听其他碰撞 }
7、碰撞中的监听(反弹力、摩擦力等属性可在此改动)bool GameScene::onContactPreSolve(PhysicsContact& contact, PhysicsContactPreSolve& solve){ // solve.setFriction(0); //摩擦力 solve.setRestitution(0); //反弹力 // solve.setSurfaceVelocity(Point(200,200)); //反弹运动方向 return true; }
8、physicsShape//能够依据刚体得到PhysicsShape,然后改动PhysicsShape属性,包含,密度反弹力等。跟在碰撞检測中改动效果一样 //Vector<PhysicsShape*> physicShape = player->getPhysicsBody()->getShapes(); Vector<PhysicsShape*> physicShape = body_player->getShapes(); for(int i=0; i<physicShape.size();i++){ physicShape.at(i)->setDensity(0); //密度 physicShape.at(i)->setRestitution(0); //反弹力 }
1、实现
Point point1(10,10); Point point2(1000,1000); Point point3 = point2;auto func = CC_CALLBACK_3(GameScene::anyRay, this); scene->getPhysicsWorld()->rayCast(func, point1, point2, &point3); //起始点、终点、保存碰撞的坐标位置 scene为開始创建的物理世界scene //以下是画红色线方便调试查看 DrawNode *_node = DrawNode::create(); this->addChild(_node); _node->drawSegment(point1, point2, 1, Color4F(1.0f, 0.0f, 0.0f, 1.0f));2、射线碰撞监听bool GameScene::anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data) { *((Point*)data) = info.contact; return false; }
cocos2d-x3.0 Physics新的物理引擎,布布扣,bubuko.com
原文:http://www.cnblogs.com/zfyouxi/p/3910814.html