Box2Dv2.1.0 user manual translation

Source: Internet
Author: User
Many of the contents are taken from the release package of Box2Dv2.0.1 User Manual Chapter 1 HelloBox2DBox2D translated by AmanJIANG (Jiang chaoyu). There is a HelloWorld program. The program creates a big ground box and a small dynamic box ). The position of the box changes with time. The Code does not involve the graphic Field

Many of the contents are taken from the Box2D v2.0.1 User Manual Chapter 1 Hello Box2D Box2D release package translated by Aman JIANG (JIANG chaoyu). There is a Hello World Program. The program creates a large ground box and a small dynamic box ). The position of the box changes with time. The Code does not involve the graphic Field

Many excerpted content
Translated by Aman JIANGBox2D v2.0.1 User Manual


Chapter 2 Hello Box2D

The release package of Box2D contains a Hello World Program. The program creates a large ground box and a small dynamic box ). The position of the box changes with time. The Code does not involve graphical interfaces. You can only view text output on the console.

This is a good example of how to use Box2D.

2.1 create a World (Creating a World)

A b2World object is created at the beginning of each Box2D program. B2World is a physical hub for managing memory, objects, and simulations. Based on your actual situation, you can create a world in the stack, stack, or data zone.

Creating a Box2D world is simple. First, we need to define the Gravity Vector and tell the world whether to allow the body to sleep at rest. The sleeping body does not need any simulation.

B2Vec2 gravity (0.0f,-10.0f );

Bool doSleep = true;

Now you can create a world object. Note: here we create the world in the stack, so the world cannot leave its scope.

B2World world (gravity, doSleep );

We already have our own physical world and began to add things to it.

2.2 create a Ground Box (Creating a Ground Box)

To create a body, follow these steps:

1. Define the body by position, damping, etc.

2. Create a body using the world object

3. Define fixture by shape, friction, and density.

4. Create fixture on the body

Step 1: Create the ground body. We need a body definition. In the definition, we specify the initial position of the ground body.

B2BodyDef groundBodyDef;

GroundBodyDef. position. Set (0.0f,-10.0f );

Step 2: Pass the body definition to the world object and create the ground body. The world object does not retain the reference of the body definition. The ground body is created as a static object. Static objects do not conflict with other static objects. They are fixed. When the body mass is zero, Box2D considers it static. The default value of object quality is zero, so they are static by default.

B2Body * groundBody = world. CreateBody (& groundBodyDef );

Step 3: create a ground polygon. We use the simple function SetAsBox to make the ground polygon form a box. The center of the box is the origin of the parent body.

B2PolygonShape groundBox;

GroundBox. SetAsBox (50366f, 10.0f );

The SetAsBox function receives half width and half height as parameters. Therefore, in this case, the ground box is 100 units wide (X axis), 20 units high (Y axis ). Box2D has been tuned to use meters, kilograms, and seconds for unit. You can think that the unit of length is meter. Box2D usually works well when the object size is the same as that in the real world. For example, a bucket is about 1 tall. Due to the limitations of the floating point algorithm, it is not a good idea to use Box2D to simulate the movements of glaciers or dust.

Step 4: Create a shape fixture to complete the ground body. In this step, we have a simple method. We do not need to modify the default material attributes of fixture. We can directly pass the shape to the body without creating the definition of fixture. In the subsequent tutorial, we will see how to use the fixture definition to customize material attributes.

GroundBody-> CreateFixture (& groundBox );

Box2D does not save the reference of shape. It copies data to a new b2Shape object.

Note that each fixture must have a parent body, even if the fixture is static. However, you can attach all static fixture to a single static body. The reason for this static body is to ensure that the code inside Box2D is more consistent and reduce the number of potential bugs.

You may have noticed that most Box2D types have b2 prefixes. This is to reduce the chance of name conflicts between it and your code.

2.3 Creating a Dynamic Body)

Now we have a ground body. We can use the same method to create a dynamic body. Apart from dimensions, we must set quality attributes for the dynamic body.

First, we use CreateBody to create the body. By default, the body is static, so b2BodyType should be set during construction to make the body dynamic

B2BodyDef bodyDef;

BodyDef. type = b2_dynamicBody;

BodyDef. position. Set (0.0f, 4.0f );

B2Body * body = world. CreateBody (& bodyDef );

Note:

If you want to exercise the body due to force impact, you must set the body type to b2_dynamicBody.

Then, we create a polygon shapde and append it to the fixture definition. First, create a box shape:

B2PolygonShape dynamicBox;

DynamicBox. SetAsBox (1.0f, 1.0f );

Next we will use box to create a fixture definition. Note that we set the density value to 1, and the default density value is 0. In addition, the friction coefficient of fixture is set to 0.3.

B2FixtureDef fixtureDef;

FixtureDef. shape = & dynamicBox;

FixtureDef. density = 1.0f;

FixtureDef. friction = 0.3f;

With the fixture definition, we can now create fixture. This will automatically update the body quality. If you like, you can add many different fixture for the body. Each fixture increases the total object quality.

Body-> CreateFixture (& fixtureDef );

This is the initialization process. Now we are ready for the simulation.

2.4 simulation (Box2D) World

We have initialized the ground box and a dynamic box. It's time for Newton to take over. We have only a few questions to consider.

Box2D uses a numerical algorithm called integrator. The Integrator simulates continuous physical equations at discrete time points. It runs together with traditional game animation loops. We need to select a time step for Box2D. Generally, the physical engine used for the game requires a speed of at least 60Hz, that is, 1/60 of the time step. You can use a larger time step, but you must be more careful with the definition of your world. We do not like the time step changes too much, so do not associate the time step with the frame rate (unless you really have to do so ). Simply put, this is the time step:

Float32 timeStep = 1.0f/60366f;

In addition to the integrator, The Box2D Code also uses the constraint solver ). The constraint solver is used to solve all the constraints in the simulation, one at a time. A single constraint will be perfectly solved, but when we solve one constraint, We will slightly delay the other. To get a good solution, We Need To iterate all the constraints multiple times.

Constraints are solved in two stages: Speed and position. In the speed stage, the solver calculates the necessary impulse to make the object correctly move. In the position phase, the solver adjusts the object location to reduce the overlap between objects. Each stage has its own iteration count. In addition, if the error is small enough, the iteration of the positional phase may exit early.

For the speed and position, the recommended number of Box2D iterations is 10. You can adjust this number as you like, but remember that it is a compromise between performance and accuracy. Fewer iterations increase the performance but reduce the accuracy. Similarly, more iterations reduce the performance but improve the simulation quality. For this simple example, we do not need to iterate multiple times. This is the number of iterations we selected.

Int32 velocityIterations = 6;

Int32 positionIterations = 2;

The time step has nothing to do with the number of iterations. An iteration is not a substep. One iteration is to traverse all constraints at a time. You can traverse the constraints multiple times in a single time step.

Now we can start to simulate the loop. In your game, the simulated loop and the game loop can be combined. Every game loop you should call b2World: Step. Generally, one call is enough, depending on the frame rate and physical time Step. After stepping, you should call b2World: ClearForces to clear any force you have applied to the body.

The Hello World Program is designed very easily and has no graphic output. The Code prints the position of the dynamic body and the rotation angle. It is better to have a text output than to have no output at all. This is the loop that simulates 60 time steps in one second:

For (int32 I = 0; I <60; ++ I)

{

World. Step (timeStep, velocityIterations, positionIterations );

World. ClearForces ();

B2Vec2 position = body-> GetPosition ();

Float32 angle = body-> GetAngle ();

Printf ("% 4.2f % 4.2f % 4.2f \ n", position. x, position. y, angle );

}

The output shows the Dynamic box landing to the ground. Your output should look like this:

0.00 4.00 0.00

0.00 3.99 0.00

0.00 3.98 0.00

...

0.00 1.25 0.00

0.00 1.13 0.00

0.00 1.01 0.00

2.5 clear

When the world object is out of its scope, or when it is deleted by a pointer, the memory allocated to the body, fixture, and joint will be released. This makes your life easier. However, you should clear the pointers of the body, fixture, or joint, because they are no longer valid.

2.6 Testbed example

Once you conquer the HelloWorld example, you should start to read the testbed of Box2D. Testbed is a unit test framework and a demo environment, which has some features:

? Mobile and zoom cameras

? Select the shape attached to a dynamic object with the mouse

? Scalable Test Set

? Select the test, adjust parameters, and set the debugging drawing through the graphic interface.

? Pause and one-step Simulation

? Text Rendering


There are many Box2D test cases in testbed and examples of the framework itself. I encourage you to study and modify it to learn Box2D.

Note: testbed is written using freeglut and GLUI. testbed itself is not part of the Box2D library. Box2D does not know how to render it. Just like the HelloWorld example, using Box2D does not have to be rendered.

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.