Box2d physical engine for cocos2dx learning ------- interaction between objects

Source: Internet
Author: User

1. Create a static object

It should be easy to create a static object. In the header file, create a function for the new object and implement it in the CPP file.

First, use the createbody function to create an object, and then define a b2bodydef variable to specify the type of the variable and position. In this case, a simple static object is created.

2. Interaction of Objects

However, although we have created two objects, we still cannot see the static objects blocking the dynamic moving objects during operation. This is because the two objects do not interact with each other.

To make two objects interact with each other, we need to set a fixture.

2. body: the body in box2d has no shape and size, and cannot be collided. It only has the basic attributes of quality (determined by the shape and density of fixture), speed, and position; body can receive Force and impulse; can attach fixture, after attachment to have shape size, can collision rebound body three types: static: No speed, no accept force and impulse; dynamic: has a speed, can accept the force and impulse effect; kinematic: has a speed, does not accept the force and impulse effect. Collision with dynamic does not change the original speed, but does not change the static collision to create the body: b2bodydef mybodydef; mybodydef. type = b2_dynamicbody; mybodydef. position. set (0, 20); m_body = m_world-> createbody (& mybodydef); 3. fixture: fixture describes the shape, density, elasticity, and friction factor of an object. The response of two objects in collision is determined by its fixture. One body can have multiple fixture, the center of gravity of the body is affected by multiple fixture values. The shape and destiny values in fixture are measured in the standard unit of meters and kilograms per square. You can refer to the actual situation when setting them; fixture has four types of shapes: b2polygonshape: polygon b2circleshape: Circular b2edgeshape: Line b2chainshape: chain (several lines connected together) friction coefficient: friction value range is 0 to 1, 0 indicates that there is no friction. 1 does not mean that there is no sliding. When two objects are rubbed, the friction size depends on the small friction restitution Elasticity: the restitution value ranges from 0 to 1. If it is 0, it indicates that there is no elasticity at all. When a collision occurs, all energy is rebounded. When two objects collide, the collision result depends on the large restitution to create friction: b2polygonshape polygonshape; polygonshape. setasbox (1, 1); b2fixturedef myfixturedef; myfixturedef. shape = & polygonshape; myfixturedef. density = 1; myfixturedef. friction = 0; // The friction factor is 0 myfixturedef. restitution = 1; // The elastic factor is 1 m_body-> createfixture (& myfixturedef );
The above code snippets also explain why you need to set Fixture for a physical system. The body looks very simple. If you want to implement some features in the real physical world, you need to set fixture.

Fixture is mainly used to set some properties of objects. It is similar to the concept of bodydef when an object was created.

When b2polygonshape shape is used, after specifying that the shape of an object is a polygon, you must set the position of the object accordingly. The setasbox. setasbox function is used to receive half width and half height. That is to say, the size of the Set object is twice the size of the parameter.

void HelloWorld::addrect(){b2BodyDef def;b2FixtureDef fixdef;b2PolygonShape shape;b2Body *b =  word->CreateBody(&def);auto sprite = Sprite::create();def.position = b2Vec2(3,5);def.type = b2_dynamicBody;shape.SetAsBox(0.5,0.5);fixdef.density = 1;fixdef.friction = 0.3;fixdef.shape = &shape;b->CreateFixture(&fixdef);addChild(sprite);sprite->setTextureRect(Rect(0,0,0.5*2*RATIO,0.5*2*RATIO));b->SetUserData(sprite);}void HelloWorld::addground(){b2BodyDef def;b2PolygonShape shape;def.position = b2Vec2(400/RATIO,0);shape.SetAsBox(400/RATIO,0.5);def.type = b2_staticBody;b2Body * body =  word->CreateBody(&def);b2FixtureDef fixdef;fixdef.density = 1;fixdef.friction = 0.3;fixdef.shape = &shape;body->CreateFixture(&fixdef);}

Two functions, one of which is to create a dynamic object and then fall down. The following function is to create a floor and a static object. Therefore, fixtrue is set to allow interaction between objects. When the attributes of an object are complete, some real physical world situations may occur.


3. Create Floating Objects

Creating a floating object is actually quite simple, but you just need to change the object type to b2_kinematicbody. Float objects are not the same as static objects. Floating objects are not controlled by the gravity of the physical world. What if you want to make a floating object truly float? It's very easy to set an initial speed for this object.

Def. linearvelocity = b2vec2 (); set an initial speed that is only along the X axis.


4. Collision Detection of Objects

Generally, a listener is required to listen to an event.

B2contactlistener is mainly used to listen for contact between objects. By implementing b2contactlistener, you can receive contact data. The contact listener supports several events: Begin, end, pre-solve, and post-solve ).

Begin event

When two fixture begin to overlap, the event is triggered. Both sensors and non-sensors trigger this event. This event can only occur in the time step (inside the function of the annotation: b2world: Step.

End event

When the two fixture parameters do not overlap, the event is triggered. Both sensors and non-sensors trigger this event. When a body is destroyed, the event may also be triggered. Therefore, this event may also occur outside of the time step.

Pre-solve event

After collision detection, the event is triggered before Collision Resolution. This will give you a chance to decide whether to invalidate the contact based on the current situation. For example, you can use b2contact: setenabled (false) in the callback to implement the single-side collision function. Each time a collision is processed, the contact will take effect again, so you should disable the contact in each time step. Due to continuous collision detection, pre-solve events may occur multiple times in a single time step.


For testing, I plan to use begin to test the effect of this listener.

Dynamic Objects will fall, so when they fall on the floor, they will certainly be in contact, so that some methods of this class can be used to detect. Setcontactlistener uses this function to create a listener. The parameter is our current class, this. Then you can implement void helloworld: begincontact (b2contact * contact) again ).

Implement the following again:

void HelloWorld::BeginContact(b2Contact* contact){ if(contact->GetFixtureA()->GetBody() == groundbody||contact->GetFixtureB()->GetBody() == groundbody){log("have a body in ground");}}

The contact object can obtain two fixture contacts and their entities. If one is a floor, it indicates that the freely falling dynamic object has collided with the floor, in this way, a message is displayed.


Box2d physical engine for cocos2dx learning ------- interaction between objects

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.