Box2dflash physical Engine

Source: Internet
Author: User

There are a lot of physical engines for flash as3. After comparison, we found that Box2D is a good open-source engine, thanks!

This engine starts from creating a world object. It is responsible for managing the memory and simulation processes of all internal objects. To create an object in the world, we first need to define a boundary area for the world. Box2D performs a simulated collision on all objects in the region. The size of the region is not important, but the more suitable area will improve the program performance. Generally, this area is set to be larger than the demo area, because once the object reaches the boundary during motion, it will be frozen and all simulation activities will be stopped.

  1. Var worldAABB: b2AABB = new b2AABB ();
  2. WorldAABB. lowerBound. Set (-100,-100); // left boundary and upper boundary
  3. WorldAABB. upperBound. Set (100,100); // right border and Bottom Border

The following code sets gravity for the world. In fact, gravity is represented by the vector b2Vec2 (x, y);, and x represents the horizontal motion, positive to the right, negative to left, y represents vertical motion, positive to downward, negative to upward. At the same time, we need to define a Boolean parameter (I name it doSleep) to indicate whether sleep is allowed. The meaning of sleep is not explicitly described on the Internet, here is a brief introduction. Because all the objects you generate in this world, their simulation results are calculated in real time. When doSleep = false, even if the object stops moving, the computer is still constantly performing operations. In fact, this is completely unnecessary, so it is generally set to true, so that when the object is stopped, no unnecessary cpu consumption will be performed.

  1. Var gravity: b2Vec2 = new b2Vec2 (0, 10 );
  2. Var doSleep: Boolean = true;

The above parameters are ready. We can pass them into the b2World object and instantiate them, so that the simulation area of a physical engine is ready.

  1. Var world: b2World = new b2World (worldAABB, gravity, doSleep );

Let's start adding the object you want to simulate. I have provided five steps on that English website, but I feel that there is nothing left, so I added another one:
Step 1: Create and define a rigid body position. Here I will give a glossary to explain how a volume or shape that does not change under any force is called a "Rigid Body ";

  1. Var ground: b2BodyDef = new b2BodyDef ();
  2. Ground. position. Set (10, 12); // The position here is also defined by a vector.

2. Define the skin for the Rigid Body (note that the skin here does not have the property of the physical engine, so the fourth step is available );

  1. BodyDef. userData = _ mc; // The image we have drawn.
  2. AddChild (bodyDef. userData );

3. Add a rigid-body instance with a world object. Note that the reference defined by the body is not saved in the world object;

  1. Var body: b2Body = world. CreateBody (bodyDef );

4. Create a simulated graphic Class Based on the skin shape: friction, density, elasticity, etc. When the density is 0, the object will not be moved, which is equivalent to obstacle. The value range of friction and elasticity is 0 ~ 1. the shape area is defined by SetAsBox, because both the simulated image and the rigid body require the registration point with the center point. Therefore, the width and height values here are both half. Pay attention to the following, here, the unit of value is not pixel, But meter, 1 meter = 30 pixels. Do not forget to convert the value when transferring the value.

  1. Var box: b2PolygonDef = new b2PolygonDef (); // create a polygon
  2. Box. density = _ density;
  3. Box. friction = _ friction;
  4. Box. restitution = _ restitution;
  5. Box. SetAsBox (_ halfWidth, _ halfHeight );

5. Add a simulated image instance to the rigid body;

  1. Body. CreateShape (box );

6. Calculate the quality based on the density and area of the rigid body. The density * Area = the quality.

  1. Body. SetMassFromShapes ();

There are two important parameters that need to be defined by ourselves. One is the number of iterations. Here I define it as m_iterations. We recommend that you set the number of iterations to 10. At this time, a reasonable value. Using a few iterations can improve the performance, but the simulation quality is affected. Similarly, the performance of more iterations is reduced, but the simulation quality is improved. Another parameter is the refresh frequency of the game. I define it as m_timeStep. According to the English document, it uses a Refresh Every 1/60 seconds, but because its platform is c ++, the performance is several times higher than that of AVM2 virtual machines. In flash, we can set it to 1/30.

  1. Var m_iterations: Number = 10;
  2. Var m_timeStep: Number = 1/30;

Now everything is ready. Let's make all objects simulate motion. In fact, it is also implemented by constantly refreshing the frame frequency by passing the above two parameters into the Step method of the world object. At the same time, we need to traverse all the objects in the world, the coordinates and angles of each object are updated.

  1. AddEventListener (Event. ENTER_FRAME, Update, false, 0, true );
  2. Function Update (e: Event): void
  3. {
  4. World. Step (m_timeStep, m_iterations );
  5. For (var bb: b2Body = world. m_bodyList; bb = bb. m_next)
  6. {
  7. If (bb. m_userData is Sprite)
  8. {
  9. Bb. m_userData.x = bb. GetPosition (). x * 30; // The unit of the variable obtained here is meter, multiplied by 30 to convert the unit of pixels.
  10. Bb. m_userData.y = bb. GetPosition (). y * 30;
  11. Bb. m_userData.rotation = bb. GetAngle () * (180/Math. PI );
  12. }
  13. }
  14. }

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.