box2d有一个名为b2ContactListener类,需要继承此类,来接收碰撞的回调。
此类为c++代码。在xcode中,需要将.m文件更改为.mm文件
//接口文件
#import "Box2D.h"
class ContactListener : public b2ContactListener
{
private:
//碰撞开始
void BeginContact(b2Contact* contact);
//碰撞结束
void EndContact(b2Contact* contact);
};
//实现文件
#import "ContactListener.h"
#import "cocos2d.h"
void ContactListener::BeginContact(b2Contact* contact)
{
b2Body* bodyA = contact->GetFixtureA()->GetBody();
b2Body* bodyB = contact->GetFixtureB()->GetBody();
CCSprite* spriteA = (CCSprite*)bodyA->GetUserData();
CCSprite* spriteB = (CCSprite*)bodyB->GetUserData();
//更改碰撞体颜色
if (spriteA != NULL && spriteB != NULL)
{
spriteA.color = ccMAGENTA;
spriteB.color = ccMAGENTA;
}
}
void ContactListener::EndContact(b2Contact* contact)
{
b2Body* bodyA = contact->GetFixtureA()->GetBody();
b2Body* bodyB = contact->GetFixtureB()->GetBody();
CCSprite* spriteA = (CCSprite*)bodyA->GetUserData();
CCSprite* spriteB = (CCSprite*)bodyB->GetUserData();
//更改碰撞体颜色
if (spriteA != NULL && spriteB != NULL)
{
spriteA.color = ccWHITE;
spriteB.color = ccWHITE;
}
}
//在刚体世界中添加监听
-(id) init
{
if ((self = [super init]))
{
//创建物理引擎世界
b2Vec2 gravity = b2Vec2(0.0f, -10.0f);
bool allowBodiesToSleep = true;
world = new b2World(gravity, allowBodiesToSleep);
//向刚体世界中添加监听
contactListener = new ContactListener();
world->SetContactListener(contactListener);
}
}
-(void) dealloc
{
//删除监听
delete contactListener;
[super dealloc];
}
此类为c++代码。在xcode中,需要将.m文件更改为.mm文件
//接口文件
#import "Box2D.h"
class ContactListener : public b2ContactListener
{
private:
};
//实现文件
#import "ContactListener.h"
#import "cocos2d.h"
void ContactListener::BeginContact(b2Contact* contact)
{
}
void ContactListener::EndContact(b2Contact* contact)
{
}
//在刚体世界中添加监听
-(id) init
{
}
-(void) dealloc
{
}