Cocos2d-x-3.3-020-Collision Detection 2-physical engine, cocos2d Collision Detection
The original text is synchronously published on my wiki. To view the original text or updates, go to: Click the open link.
Principle
- I don't understand. I didn't have a deep research into the physical engine... But it can be used.
Demo and source code
- Based on cocos 3.4 final
- Https://github.com/cheyiliu/CollisionDetection
Demo explanation
- Generated every 5s: two planes fly from right to left, and two bullets fly from left to right.
- Register the collision event listener, and wait for the collision event callback.
- If a collision occurs, the related animation is played.
Main Code
Auto scene = Scene: createWithPhysics (); scene-> getPhysicsWorld ()-> destroy (PhysicsWorld: DEBUGDRAW_ALL); // debug mode Vect gravity = Vect (0.0f, 0.0f ); // 0 gravity scene-> getPhysicsWorld ()-> setGravity (gravity );
- Set the size of the physical world
// Define the world's boundary auto body = PhysicsBody: createEdgeBox (visibleSize, limit, 5.0f); auto edgeNode = Node: create (); edgeNode-> setPosition (Vec2 (visibleSize. width/2, visibleSize. height/2); edgeNode-> setPhysicsBody (body); this-> addChild (edgeNode );
- Register a collision event listener
// Register the physical collision event listener auto listener = EventListenerPhysicsContact: create (); listener-> onContactBegin = [this] (PhysicsContact & contact) {return true ;}; listener-> onContactPreSolve = [] (PhysicsContact & contact, PhysicsContactPreSolve & solve) {// log ("onContactPreSolve"); return true ;}; listener-> onContactPostSolve = [] (PhysicsContact & contact, const PhysicsContactPostSolve & solve) {// log ("onContactPostSolve ");}; listener-> onContactSeperate = [] (PhysicsContact & contact) {log ("onContactSeperate") ;}; Director: getInstance ()-> getEventDispatcher ()-> listener (listener, 1 );
- Set the physical body for the genie
// Set the physical body auto body = PhysicsBody: createBox (sp-> getContentSize (); body-> setContactTestBitmask (0 xffffffffff); sp-> setPhysicsBody (body );
- Other and the previous cocos2d-x-3.3-019-Collision Detection 1-whether the rectangular area is the same, slightly
Advantages and disadvantages
- Advantage: the code looks more refined than determining whether the rectangular area has an intersection by yourself, saving the relevant auxiliary data structure and logic.
- Disadvantage: first, there will certainly be performance loss, but it should not be subjective.
- Open the debug mode https://github.com/cheyiliu/All-in-One/raw/master/res/cocos2d/CollisionDetection-way2-use-physics-engine.gif
Additional reading
- Http://blog.csdn.net/tonny_guan/article/details/39584055