Introduction to Box2D physical engine: Collision Detection in Cocos2d-x

Source: Internet
Author: User

Introduction to Box2D physical engine: Collision Detection in Cocos2d-x
In Box2D, collision events are implemented by implementing b2ContactListener class functions. b2ContactListener is an abstract class provided by Box2D, and its abstract function:
Virtual void BeginContact (b2Contact * contact ). The two objects will respond when they begin to contact each other, but they are called only once.
Virtual void EndContact (b2Contact * contact ). Response when splitting. But it is called only once.
Virtual void PreSolve (b2Contact * contact, const b2Manifold * oldManifold ). Response during continuous contact, which is called multiple times.
Virtual void PostSolve (b2Contact * contact, const b2ContactImpulse * impulse ). Response during continuous contact, called after preSolve is called.
The following describes how to detect collision in the Box2D physical engine by restructuring the instance in section 12.2.3 using Box2d technology.
First, we need to add a new class in the project. To add a new class to Visual Studio 2012, you must add the C ++ source file and header file respectively. For more information, right-click the Classes folder under the HelloBox2D project, right-click the folder, and choose "add"> "new project" from the shortcut menu ". The add new project dialog box is displayed, as shown in the following figure. In the dialog box, select the file type, enter the file name ContactListener in "name", and click "add" to add the file.

Add a new class in Visual Studio 2012
In the Add new project dialog box, add the new class ContactListener. We also need to modify its code. The ContactListener. h file code is as follows:

# Include cocos2d. h # include Box2D/Box2D. hUSING_NS_CC; class ContactListener: public b2ContactListener {private: // The virtual void BeginContact (b2Contact * contact) is returned when two objects start to contact ); // respond to virtual void PreSolve (b2Contact * contact, const b2Manifold * oldManifold) during continuous contact; // respond to persistent contact. Call virtual void PostSolve (b2Contact * contact after calling preSolve, const b2ContactImpulse * impulse); // returns the virtual void EndContact (b2Contact * contact) When splitting) ;}; The header files cocos2d. h and Box2D/Box2D. h must be introduced to the header files; otherwise, compilation errors may occur. ContactListener inherits b2ContactListener. ContactListener. the cpp file code is as follows: # include ContactListener. hvoid 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) 7 {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) implements {log (PreSolve);} void ContactListener: PostSolve (b2Contact * contact, const b2ContactImpulse * impulse) implements {log (PostSolve );}


The first line of the above Code implements the incontact function of the collision event. The second line of code and the third line of code are used to obtain objects that are in contact with both parties. Code ④ and line ⑤ determine the genie object from the UserData attribute of the object. The UserData attribute can be used to place any object. here we can use bodyA-> GetUserData () when defining an object, you can use the body-> SetUserData (sprite) statement to put the sprite into the UserData attribute of the object. The sixth line of code is to determine whether two elves exist.
Line 7 of the Code implements the collision event EndContact function, which is similar to the BeginContact function. The code in the second and second rows implements the collision event PreSolve and PostSolve functions, which are usually not used much.
We also need to add the relevant collision detection code in the layer to listen to the event. The code in HelloWorld. h is as follows:
#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include cocos2d.h#include Box2D/Box2D.h#include ContactListener.h①#define PTM_RATIO 32class 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__


The first line of the above Code is to introduce the header file ContactListener. h. The Code in line ② declares the member variable ContactListener of the contactListener type.
We also need to modify the HelloWorld: initPhysics () code in HelloWorld. cpp as follows:
void HelloWorld::initPhysics(){… …   contactListener = new ContactListener();world->SetContactListener(contactListener);… …}


The contactListener = new ContactListener () Statement in the function is used to create a ContactListener object. The new keyword is used to allocate memory. To create a member variable contactListener, you must release the contactListener object by yourself. The release process is performed in the destructor. Its destructor code is as follows:
HelloWorld ::~ HelloWorld ()
{
CC_SAFE_DELETE (world );
CC_SAFE_DELETE (contactListener );
}

Use CC_SAFE_DELETE (contactListener) to safely release the memory of the contactListener member variable.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.