介绍
在3.2的重力系统,创建场景就不能用Scence *s = Scence::create(); 要用:Scence *s = Scence::createWithPhysics();
bool T07PhysicsWorld::init()
{
Layer::init();
PhysicsBody* bodyA;
PhysicsBody* bodyB;
{
//createCircle 创建一个圆形的body
PhysicsBody* body = PhysicsBody::createCircle(20, PhysicsMaterial(1.0f, 1.0f, 0.0f));//PhysicsMaterial(密度,弹力,摩擦力)
bodyA = body;
Sprite* sprite = Sprite::create();
#if 0
/*
此处精灵看不见,因为没有具体的精灵,在3.2里我们可以把这个body的边框画出来,在场景那边设置下:
Scene* s = Scene::createWithPhysics();
//就是下面这两句
PhysicsWorld* world = s->getPhysicsWorld();//取出世界
world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
*/
#endif
sprite->setPhysicsBody(body);
addChild(sprite);
sprite->setPosition(winSize.width / 2, winSize.height / 2);
//设置速度,在x, y方向的速度。
body->setVelocity(Vect(100, 200));
}
{
//加四边形边框
PhysicsBody* body = PhysicsBody::createEdgeBox(winSize, PhysicsMaterial(1.0f, 1.0f, 0.0f));
bodyB = body;
Sprite* sprite = Sprite::create();
addChild(sprite);
sprite->setPhysicsBody(body);
sprite->setPosition(winSize.width / 2, winSize.height / 2);
}
//碰撞检测
{
//body碰撞要设置BitMask,表示这个body要不要计算碰撞
bodyA->setContactTestBitmask(0x1);
bodyB->setContactTestBitmask(0x1);
//设置是哪个组的。组与组之间碰撞检测,组内部不做碰撞检测。
bodyA->setGroup(1);
bodyB->setGroup(2);
//碰撞检测
auto ev = EventListenerPhysicsContactWithBodies::create(bodyA, bodyB);
//当碰撞开始时调用此函数
ev->onContactBegin = [](PhysicsContact& contact){
CCLog("Began Contact...........");
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(ev, this);
}
//也可以通过形状做碰撞检测
{
//一个body对应多个Shapes
auto ev = EventListenerPhysicsContactWithShapes::create(bodyA->getShapes().at(0),
bodyB->getShapes().at(0));
ev->onContactBegin = [](PhysicsContact& contact){
CCLog("Shape Began Contact...........");
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(ev, this);
}
{
auto ev = EventListenerPhysicsContactWithGroup::create(3); //3是Gid等于3的有碰撞,就调用。类推。
ev->onContactBegin = [](PhysicsContact& contact){
CCLog("Group Began Contact...........");
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(ev, this);
}
return true;
}
一个body可以对应多个shape,比如复杂的形状可以拆分为几个shape,如乌龟可以将头和脚等分开。
{
PhysicsBody* body = PhysicsBody::create();
PhysicsShape* shape1 = PhysicsShapeBox::create(Size(40, 40), PHYSICSBODY_MATERIAL_DEFAULT, Vec2::ZERO);
body->addShape(shape1);
PhysicsShape* shape2 = PhysicsShapeCircle::create(10, PHYSICSBODY_MATERIAL_DEFAULT, Vec2(-30, 0));
body->addShape(shape2);
// Sprite* sprite = Sprite::create();
Node* node = Node::create();
node->setPhysicsBody(body);
addChild(node);
node->setPosition(winSize.width / 2, winSize.height / 2);
}
// 边框
{
PhysicsBody* body = PhysicsBody::createEdgeBox(winSize, PhysicsMaterial(1.0f, 1.0f, 0.0f));
Sprite* sprite = Sprite::create();
addChild(sprite);
sprite->setPhysicsBody(body);
sprite->setPosition(winSize.width / 2, winSize.height / 2);
}