cocos2d -x 3.2 碰撞响应

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;
}


实现碰撞处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值