#include "cocos2d.h" #include "Box2D/Box2D.h" USING_NS_CC; class ContactListener : public b2ContactListener { private: //两个物体开始接触时会响应 virtual void BeginContact(b2Contact* contact); //持续接触时响应 virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); //持续接触时响应,调用完preSolve后调用 virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); //分离时响应 virtual void EndContact(b2Contact* contact); }; 在头文件中需要引入cocos2d.h和Box2D/Box2D.h头文件,否则会有编译错误。ContactListener采用共有继承b2ContactListener。 ContactListener.cpp文件代码如下: #include "ContactListener.h" void ContactListener::BeginContact(b2Contact* contact) ① { log("BeginContact"); b2Body* bodyA = contact->GetFixtureA()->GetBody(); ② b2Body* bodyB = contact->GetFixtureB()->GetBody(); ③ auto spriteA = (Sprite*)bodyA->GetUserData(); ④ auto spriteB = (Sprite*)bodyB->GetUserData(); ⑤ if (spriteA != nullptr && spriteB != nullptr) ⑥ { spriteA->setColor(Color3B::YELLOW); spriteB->setColor(Color3B::YELLOW); } } void ContactListener::EndContact(b2Contact* contact) ⑦ { log("EndContact"); b2Body* bodyA = contact->GetFixtureA()->GetBody(); b2Body* bodyB = contact->GetFixtureB()->GetBody(); auto spriteA = (Sprite*)bodyA->GetUserData(); auto spriteB = (Sprite*)bodyB->GetUserData(); if (spriteA != nullptr && spriteB != nullptr) { spriteA->setColor(Color3B::WHITE); spriteB->setColor(Color3B::WHITE); } } void ContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) ⑧ { log("PreSolve"); } void ContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) ⑨ { log("PostSolve"); }
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "Box2D/Box2D.h" #include "ContactListener.h" ① #define PTM_RATIO 32 class HelloWorld : public cocos2d::Layer { b2World* world; ContactListener* contactListener; ② public: ~HelloWorld(); static cocos2d::Scene* createScene(); virtual bool init(); virtual void update(float dt); virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); CREATE_FUNC(HelloWorld); void initPhysics(); void addNewSpriteAtPosition(cocos2d::Vec2 p); }; #endif // __HELLOWORLD_SCENE_H__
void HelloWorld::initPhysics() { … … contactListener = new ContactListener(); world->SetContactListener(contactListener); … … }
使用CC_SAFE_DELETE(contactListener)安全释放contactListener成员变量的内存。
欢迎关注智捷iOS课堂微信公共平台
原文地址:http://blog.csdn.net/tonny_guan/article/details/39936067