Cocos2d-x 3.x physical collision mechanism

Source: Internet
Author: User

Cocos2d-x 3.x physical collision mechanism

I recently got another physical engine. Let's write it down. Next we will summarize the knowledge I learned from other blogs and my understanding.

The brand new encapsulated physical engine in cocos2d-x 3.X gives developers the greatest convenience, you don't have to bother with the details of various physical engines, the complete encapsulation allows developers to add physical engine mechanisms to their own games faster and better. The simplified design is from 2.0 to 3. X is a qualitative leap.

 

 

Physical Properties in cocos2d-x 3.0 +:

1. the physical world is integrated into the scenario. When you create a scenario, you can directly create a scenario based on the physical world or without using the physical world.

2. Node has its own body attribute. (Sprite is also a node )'

3. cocos2d-x 3.0 has encapsulated the physical attributes Body (PhysicsBody), Shape (PhysicsShape), Contact (PhysicsContact), Joint (PhysicsJoint) and World (PhysicsWorld) for more convenient use.

4. Use listener-EventListenerPhysicsContact for collision detection.

Of course, the encapsulated physical engine can simplify development. If you have the ability, you can directly use the native physical engine of Box2D and Chipmunk for development. This will increase the difficulty.

The following code creates a scenario with a physical world and passes it to the layer in the scenario.

PhysicsLayer. h

 

[Cpp]
  1. Class PhysicsLayer: public cocos2d: Layer
  2. {
  3. ...
  4. // Add following codes to set the physical world in the layer
  5. Void setPhyWorld (PhysicsWorld * world) {m_world = world ;}
  6.  
  7. Private:
  8. PhysicsWorld * m_world;
  9. ...
  10. } Add the following code to the createScene () method in PhysicsLayer. cpp:

     

     

    [Cpp]
    1. Scene * PhysicsLayer: createScene ()
    2. {
    3. ...
    4. // Add following codes
    5. Auto scene = Scene: createWithPhysics ();
    6. Scene-> getPhysicsWorld ()-> setDebugDrawMask (PhysicsWorld: DEBUGDRAW_ALL); // debug
    7.  
    8. Auto layer = HelloWorld: create ();
    9. Layer-> setPhyWorld (scene-> getPhysicsWorld (); // transmits the created physical world to the child layer.
    10. Scene-> addChild (layer );
    11. Return scene;
    12. }

       

      The Scene class has a new static factory method createWithPhysics () to create a scenario with a physical world. You can use getPhysicsWorld () to obtain PhysicsWorld instances.

      The Code Annotated as debugging in the above code is very useful in debugging. It will display the physical boundaries of the objects in the game, so as to facilitate observation of the details in the collision.

      At the same time, there can only be one physical world in a scenario. All the child layers in this scenario share this physical world. Therefore, this defined function is used in the child layer when the physical world is used.

       

      [Cpp]
      1. Void setPhyWorld (PhysicsWorld * world) {m_world = world;} to set the physical world in the child layer.

         

        PhysicsWorld has the default gravity setting, which is Vector (0.0f,-98.0f). Of course, you can also set the desired gravity acceleration, setGravity (Vect (0.0f,-200366f )), set the gravity acceleration to 20 meters per second.

        The code below the physical boundary is used to create a physical boundary.[Cpp]View plaincopy
        1. Size visibleSize = Director: getInstance ()-> getVisibleSize ();
        2. Auto body = PhysicsBody: createEdgeBox (visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); // set the physical body to be added to the node. This Box is not subject to collision detection !!!
        3. Auto edgeNode = Node: create ();
        4. EdgeNode-> setPosition (Point (visibleSize. width/2, visibleSize. height/2 ));
        5. EdgeNode-> setPhysicsBody (body); // Add the physical body to the created node.
        6. Scene-> addChild (edgeNode); there are many factory methods to add the created physical node PhysicsWorld in the scenario. For example, createEdgeBox creates a rectangle border. parameters: 1. rectangle area, set as VisibleSize 2. optional parameter. Physical material. The default value is PHYSICSBODY_MATERIAL_DEFAULT. 3. Optional parameters and border size. The default value is 1. Create a gravity-affected Genie and create a gravity-affected genie for the code below. The creation genie code in section 3.0 is also greatly simplified.[Cpp]View plaincopy
          1. Void HelloWorld: addNewSpriteAtPosition (Point p)
          2. {
          3. Auto sprite = Sprite: create(circle.png); // create an genie
          4. Sprite-> setTag (1); // you can specify the signature value for the sprite.
          5. Auto body = PhysicsBody: createCircle (sprite-> getContentSize (). width/2); // create a circular physical body attached to the genie body
          6. Sprite-> setPhysicsBody (body); // Add the created body to the sprite.
          7. Sprite-> setPosition (p );
          8. This-> addChild (sprite); // Add a genie
          9. } Next, let's take a look at the real focus: the physical engine is used in the last NotOneLess project. In fact, the collision detection of the physical engine is the setting of three mask attribute values, back and forth is set worthy of the problem, understand this, physical collision learned 80% understand this: Click to open the link http://www.tuicool.com/articles/nAZbuy below code registration Collision Response event and callback function[Cpp]View plaincopy
            1. Auto contactListener = EventListenerPhysicsContact: create ();
            2. ContactListener-> onContactBegin = CC_CALLBACK_1 (HelloWorld: onContactBegin, this );
            3. _ EventDispatcher-> addEventListenerWithSceneGraphPriority (contactListener, this); for each collision detection event, EventListenerPhysicsContact is used for listening. When a collision event is monitored, the system calls back the onContactBegin () event to handle the collision event. _ EventDispatcher is an event dispatcher that manages all registered events. EventListenerPhysicsContact is a type of collision detection. You can also use the following methods to register collision events, EventListenerPhysicsContactWithShapes, EventListenerPhysicsContactWithGroup, to listen to bodys, shape, and group events you are interested in. As mentioned above, the most important thing is the following. If there is no such thing, the collision event does not work at all. This is the problem I encountered when I used the collision for the first time. That is, set the bitmask value related to the physical contact. The default contact event will not be accepted. You need to set a certain mask value to respond to the contact event. The contact mask value has three values: 1. CategoryBitmask. The default value is 0 xFFFFFFFF. 2. ContactTestBitmask. The default value is 0x00000000. 3. CollisionBitmask, the default value is 0 xFFFFFFFF. All three mask values have the corresponding set/get method to set and obtain. The three mask values are tested by logic and operations.
              When the logic of the CategoryBitmask of one body and the ContactTestBitmask of another body are not equal to 0, the contact event is sent; otherwise, the contact event is not sent.
              When the logic and result of CategoryBitmask of one body and CollisionBitmask of another body are not equal to 0, they will collide, otherwise they will not collide
              By default, the body attribute will perform a physical collision, but will not send a collision detection signal, and will not respond to the collision callback function. This can be seen in the logic of the default mask value and[Cpp]View plaincopy
              1. CategoryBitmask = 0 xFFFFFFFF;
              2. ContactTestBitmask = 0x00000000;
              3. CategoryBitmask & ContactTestBitmask = 0, so no collision signal is sent
              4.  
              5. CollisionBitmask = 0 xFFFFFFFF;
              6.  
              7. CategoryBitmask & CollisionBitmask = 0 xFFFFFFFF
              8. Therefore, objects will collide, but will not respond to the collision callback function. The mask value described above is the most important in the collision detection callback. Without the above mask value, all collision callback functions will not happen. EventListenerPhysicsContact has four contact callback functions: 1. onContactBegin, called at the beginning of the contact. It is called only once. Whether the two objects have a collision is determined by putting back true or false. You can also use PhysicsContact: setData () to set the user data for the contact operation. When false is returned, onContactPreSolve and onContactPostSolve will not be called, but onContactSeperate will be called once. 2. onContactPreSlove will be called at each time. By Returning true or false to determine whether two objects have collided, ignore () can also be used to skip subsequent onContactPreSolve and onContactPostSolve callback functions. (True is returned by default) 3. onContactPostSolve is processed and called in each step of the collision reaction between two objects. You can perform subsequent contact operations in it. For example, destroy body 4 and onContactSeperate. They are called when two objects are separated. They are called only once at each contact and paired with onContactBegin. The most important thing above is the explanation of collision detection events, which are frequently used in games. Okay. This article explains the physical collision mechanism in the game.

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.