auto ballOne = Sprite::create("Ball.png");
ballOne->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
auto size = ballOne->getContentSize();
auto ballOneBody = PhysicsBody::createCircle(size.width/2,PHYSICSBODY_MATERIAL_DEFAULT);
//ballOneBody->setDynamic(false);
ballOneBody->getShape(0)->setRestitution(1.0f);
ballOneBody->getShape(0)->setFriction(0.0f);
ballOneBody->getShape(0)->setDensity(1.0f);
//ballOneBody->getShape(0)->setMass(5000);
<span style="color:#ff0000;">ballOneBody->getShape(0)->setContactTestBitmask(0x01);
</span> ballOneBody->setGravityEnable(false);
Vect force = Vect(500000.0f, 500000.0f);
ballOneBody->applyImpulse(force);
ballOne->setPhysicsBody(ballOneBody);
ballOne->setTag(1);
this->addChild(ballOne);
//增加第二个小球
auto ballTwo = Sprite::create("Ball2.png");
ballTwo->setPosition(Point(visibleSize.width/3,visibleSize.height/3));
//auto size = ballTwo->getContentSize();
auto ballTwoBody = PhysicsBody::createCircle(size.width/2,PHYSICSBODY_MATERIAL_DEFAULT);
//ballOneBody->setDynamic(false);
ballTwoBody->getShape(0)->setRestitution(1.0f);
ballTwoBody->getShape(0)->setFriction(0.0f);
ballTwoBody->getShape(0)->setDensity(1.0f);
//ballTwoBody->getShape(0)->setMass(5000);
ballTwoBody->setGravityEnable(false);
<span style="color:#ff0000;">ballTwoBody->getShape(0)->setContactTestBitmask(0x01);
</span> Vect force2 = Vect(-500000.0f, -500000.0f);
ballTwoBody->applyImpulse(force2);
ballTwo->setPhysicsBody(ballTwoBody);
ballTwo->setTag(2);
this->addChild(ballTwo);
增加两个小球,设置物理属性
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener,this);
增加监听
bool HelloWorld::onContactBegin(const PhysicsContact& contact)
{
CCLog("enter a contact");
Sprite* spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode();
Sprite* spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode();
int tagA = spriteA->getTag();
int tagB = spriteB->getTag();
if(tagA==1&&tagB==2 || tagA==2&&tagB==1)
{
spriteA->removeFromParent();
spriteB->removeFromParent();
}
return true;
}
实现碰撞处理