Example: Cocos2d-x physical engine: collision detection, cocos2d-x Collision Detection

Source: Internet
Author: User
Tags bitmask

Example: Cocos2d-x physical engine: collision detection, cocos2d-x Collision Detection
Collision detection is an important purpose of using the physical engine. Using the physical engine can perform precise collision detection, and the execution efficiency is also high.
Use the event dispatch mechanism in Cocos2d-x 3.x to manage collision events, and EventListenerPhysicsContact is the collision event listener. The collision detection APIs are described in the previous section. The following example describes the implementation of collision detection. In the running scenario of this instance, after the scenario is started, the player can touch and click the screen. Each time the screen is touched, a new genie will be generated at the touch point, the running of the genie is a free-body movement. When these genie are in contact with each other, their colors are set to yellow. After separation, the colors are restored to their original state.


Detection and collision instance this instance involves the detection and collision between objects in the physical engine. When two objects are exposed to the separation of two objects, some events may occur, we can register the listener EventListenerPhysicsContact to respond to these events.
First, let's take a look at the HelloWorldScene. h file. Its code is as follows:

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"USING_NS_CC;class HelloWorld : public cocos2d::Layer{public:    static cocos2d::Scene* createScene();    virtual bool init();  virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);virtual void onEnter();virtual void onExit();        CREATE_FUNC(HelloWorld);void addNewSpriteAtPosition(Vec2 p);};#endif // __HELLOWORLD_SCENE_H__


The above Code declares the onEnter and onExit functions, which are used to process the callback functions that the layer enters and exits. We will register the EventListenerPhysicsContact listener in the onEnter function to respond to collision detection events and deregister These listeners in the onExit function.
HelloWorldScene. the boundary statements used to create the physical world and the specified world in cpp are in the HelloWorld: createScene () and HelloWorld: init () functions. These two functions are similar to the HelloPhysicsWorld instance in the previous section, the function code will not be explained here.
The collision detection-related code in HelloWorldScene. cpp is in the onEnter and onExit functions. The Code is as follows:
void HelloWorld::onEnter(){Layer::onEnter();auto listener = EventListenerPhysicsContact::create();listener->onContactBegin = [](PhysicsContact& contact)①{auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode();②auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode();③if (spriteA && spriteA->getTag() == 1 && spriteB && spriteB->getTag() == 1) ④{spriteA->setColor(Color3B::YELLOW);spriteB->setColor(Color3B::YELLOW);}log("onContactBegin");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) {⑦auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode();auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode();if (spriteA && spriteA->getTag() == 1 && spriteB && spriteB->getTag() == 1) {spriteA->setColor(Color3B::WHITE);spriteB->setColor(Color3B::WHITE);}log("onContactSeperate");};Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener,1); ⑧}void HelloWorld::onExit(){Layer::onExit();log("HelloWorld onExit");Director::getInstance()->getEventDispatcher()->removeAllEventListeners();⑨}


The onEnter () function of the above Code is the callback function when entering the scenario. here we can use the auto listener = EventListenerPhysicsContact: create () statement to create the object collision detection event listener object. Next, use the Lambda expressions in rows ①, ⑥, ⑤, and 7 to define the anonymous functions for event processing.
Lines ② and ③ of the Code are two node objects that interact with each other from the contact point. The value process is a bit complicated. First, the contact points use getShapeA () and getShapeB () the function obtains the shape of an object, obtains the object through the getBody () function of the shape, and obtains the Node object related to the shape through the getNode () function of the object. The fourth line of code is to judge whether the Node object retrieved from the contact point exists and whether the tag attribute is 1.
The addEventListenerWithFixedPriority of the above Code specifies a fixed event priority to register the listener. The event priority determines the priority of the event response. The smaller the value, the higher the priority.
The Nth line of the Code cancels all listening events in the exit layer callback function onExit.
In HelloWorldScene. cpp, there are two functions, onTouchBegan and addNewSpriteAtPosition. Their code is as follows.
bool HelloWorld::onTouchBegan(Touch* touch, Event* event){Vec2 location = touch->getLocation();addNewSpriteAtPosition(location);return false;}void HelloWorld::addNewSpriteAtPosition(Vec2 p){    auto sp = Sprite::create("BoxA2.png");sp->setTag(1);auto body = PhysicsBody::createBox(sp->getContentSize());body->setContactTestBitmask(0xFFFFFFFF);①sp->setPhysicsBody(body);sp->setPosition(p);this->addChild(sp);}


The Code of these two functions is basically the same as that of the instance described in the previous section, but note that we added the body-> setContactTestBitmask (0 xffffffffff) Code in line ①, it is used to set whether the collision detection event defined in EventListenerPhysicsContact can be triggered during object contact. If the contact test mask (ContactTestBitmask) of the two objects performs the "logical and" operation and the result is a non-zero value, the two objects will trigger a collision detection event. The default value is 0x00000000, indicating that all mask bits are cleared. 0xFFFFFFFF indicates that all mask bits are set to 1.
Assume there are three objects (body1, body2, and body3). Set the contact test mask as follows:
Body1-> setContactTestBitmask (0x01); // 0001
Body2-> setContactTestBitmask (0x03); // 0011
Body3> setContactTestBitmask (0x02); // 0010
Therefore, body1, body2, and body2 and body3 can trigger the EventListenerPhysicsContact collision detection event, while body1 and body3 cannot.
In addition to ContactTestBitmask, the physical engine also defines CategoryBitmask and CollisionBitmask ), they are used to determine whether a "collision reaction" occurs when two objects are in contact with each other. The "collision reaction" indicates that an object is subject to another collision and changes the direction of motion. Because the two objects are "rigid bodies", the two objects do not overlap during the collision.
So what is the category mask (CategoryBitmask) and the collision mask (CollisionBitmask?
1. Category mask
Defines the category of an object. Each object can be assigned to up to 32 different categories in a scenario. Use the body-> setCategoryBitmask (int bitmask) function to set the category mask.
2. Collision mask
When two objects are in contact with each other, the collision mask of the object and the category mask of the other object perform the "logic and" operation. If the result is a non-zero value, this object can respond to the collision of another object. The collision mask set through the body-> setCollisionBitmask (int bitmask) function.
To sum up, the CategoryBitmask and CollisionBitmask determine whether an object can undergo a "collision reaction ". The ContactTestBitmask setting can detect whether a contact occurs and trigger an EventListenerPhysicsContact listener event. The contact test mask is not associated with the category mask and collision mask.
Suppose there are three objects (body1, body2, and body3), they are set as follows:
body1->setCategoryBitmask(0x01);//0001body1->setCollisionBitmask(0x03);//0011body2->setCategoryBitmask(0x02);//0010body2->setCollisionBitmask(0x01);//0001body3->setCategoryBitmask(0x04);//0100body3->setCollisionBitmask(0x06);//0110


Body1 and body1, body1 and body2, body3 and body3 can collide with each other, and body1 and body3 cannot crash. Box 2 cannot respond to the box3 collision, but box 3 can respond to the box2 collision.



More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to Cocos2d-x Technology Discussion Group: 257760386

Welcome to Zhijie iOS public classroom Platform



Physical detection collision callback in cocos2d-x


I generally write a closure function, so there is no problem with this writing.


 
Cocos2d-x Collision Detection

1. Why should I use an anchor as the anchor?

2. Are you separate the two codes? The following section should be in update

3. I don't know what action you are running. Are you sure you can hit it? Increase the width and height to see if the output is yes.

4. This yes may be output under the tool or in a black box in the background. Have you read it?

5. How good is box2d for collision detection ~ Simple call and precise determination

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.