Get started with jbox2d to learn about the physical world and the simplest object Creation

Source: Internet
Author: User

This weekend I was bored. I went back to my roommate's book on game development and browsed it.

Because the game has never been used to it before, you may simply know the simple concept of game plotting, logic, and game framework drawing on one side.

This is mainly to see the most common and basic physical engine in Game Development, box2d.

For this engine, it may be best to show and express its purpose. I think crazy birds are the best example.

In the bird, the bird hits the rock to generate object motion.

What if we do it ourselves?

1. When a bird is popped up, we have to follow the gravity, initial velocity, and resistance friction of the bird. In general, this is not very clear about physics, and it is quite troublesome, because I almost forgot about physics in junior high school.

2. Detection of collision when birds touch the rock heaps. Then we need to always calculate whether the pixel area of the bird object is overlapped with the pixel of a rock, that is, collision.

3. What happens after the collision? It is necessary to simulate the effect of motion changes on the object after the impact. It must be involved here. Only a series of problems such as density, collision recovery force, and friction between different objects can we simulate the effects of the entire post-impact object operation.

Then box2d completely simulates various events of objects in this physical world, you only need to obtain the simulated state parameters (usually coordinates and angles) of an object in the physical world several times per second, and then draw the object on the screen.

Box2d has different language versions. Here we only introduce this version in Android development, jbox2d.

In fact, box2d is not complicated to get started, because it basically looks at the definition of the physical world, creates, and creates object definitions. It may be a day.

However, if more parameters are involved, the details and parameters involved may be very large for an object in reality, if you want to simulate a physical world close to the real world, it is quite well studied how to define these parameter values.

The following is what I spent an afternoon studying on Saturday. Take notes by the way.

**************************************** **************************************** **********************************/

Concepts of box2d.

Basic class world, AABB, body, shapedef, bodydef

I. Creation of the world

First, for box2d, the most important thing is to create a physical world to manage and simulate the state of all objects in the world.

AABB aabb = new AABB();aabb.lowerBound = new Vec2(-100, -100);aabb.upperBound = new Vec2(100, 100);Vec2 gravity = new Vec2(0, 10);world = new World(aabb, gravity, true);

Step 1: Use the AABB instance to set the boundary of the world and stop the simulation of an object outside the boundary.

Second, create a world object. The input three parameters are represented respectively. AABB specifies the world boundary, the gravity vector of the gravity world, and the third is whether an object is allowed to sleep after it stops motion, without simulating it.

2. Create an object in the world.

Three classes involved in creating a rigid body:

Shapedef class and Shape Definition class (of course we usually use its subclass .) It is strange to define this class as a shape definition, because the force density of the friction force on the object is specified by its class. It may be said that we generally think that the shape definition may be the external structure of the object, and the friction may be defined here, because the friction may involve the characteristics of the external surface of the object. For density, I always think it is a special attribute of an object.

Bodydef class, rigid body definition class. It is mainly used to describe the object location and angle.

Body class, a rigid body class, that is, a rigid body instance is completed through Shape Definition and rigid body definition.

An object can be created in three steps.

Public static body createpolygon (World, float X, float y, float W, float H, float angle, float density) {polygondef Pd = new polygondef (); PD. density = density; // density PD. friction = 0.8f; // friction PD. restitution = 0.7f; // recovery force PD. setasbox (W/2/constant. rate, H/2/constant. rate); bodydef BD = new bodydef (); BD. position. set (x + W/2)/constant. rate, (Y + H/2)/constant. rate); BD. angle = (float) (angle * Math. (PI/180); Body = World. createbody (BD); body. m_userdata = new myrect (X, Y, W, H); body. createshape (PD); body. setmassfromshapes (); return body ;}

Polygondef is a subclass of shapedef and is called a polygon description class. Defines the density, friction, and recovery power (it refers to the elastic deformation that we learned in junior high school. We will know it after several attempts ).

Setasbox is used to quickly create a shape box. The input parameter is the length and width of the box to be created. This is basically written to death, that is, half of it. To know why it is like drawing on the paper, the internal logic processing of box2d feels that the input parameter is the easiest to draw.

Bodydef, defined by a rigid body, sets the coordinates of an object in the physical world. On the screen, we use the point in the upper left corner of the object as (x, y). In the early physical world, we use the center point of the object. So what we pass in is (x, y). If we want to draw an object at last the same way as we originally imagined, we need to move the object length to X and Y respectively, the width is half the width of the image. (The effect is quite clear after practice ).

Body, which generates an object in the world according to the definition of the Rigid Body and the definition of the shape through the physical world factory.

So far, a physical world and a simple object creation method in the physical world are implemented.

The next step is to process the drawing and logic processing code in the game framework.

Private void draw () {try {canvas = holder. lockcanvas (); canvas. drawcolor (color. black); // clear the screen // draw the background canvas. drawbitmap (bitmapbg, 0, 0, paint); // traverses and draws the body = World. getbodylist (); For (INT I = 1; I <world. getbodycount (); I ++) {If (body. m_userdata) instanceof myrect) {myrect rect = (myrect) (body. m_userdata); rect. drawrect (canvas, paint);} If (body. m_userdata) instanceof mystone) {mystone Title = (myst One) (body. m_userdata); title. drawstone (canvas, paint);} body = body. m_next; }} catch (exception e) {}finally {try {If (canvas! = NULL) Holder. unlockcanvasandpost (canvas);} catch (exception E2) {}}/ *** logic */private void logic () {world. STEP (constant. steptime, constant. iterations); // traverses the body and transmits the data body = world between the body and the image. getbodylist (); For (INT I = 1; I <world. getbodycount (); I ++) {// determines whether the data in m_userdata is myrect instance if (body. m_userdata) instanceof myrect) {myrect rect = (myrect) (body. m_userdata); rect. setx (body. getposition (). x * constant. rate-rect. getw ()/2); rect. sety (body. getposition (). y * constant. rate-rect. geth ()/2); rect. setangle (float) (body. getangle () * 180/math. pi);} else if (body. m_userdata) instanceof mystone) {// determines whether the data in m_userdata is mytile instance mystone tile = (mystone) (body. m_userdata); tile. setx (body. getposition (). x * constant. rate-tile. getw ()/2); tile. sety (body. getposition (). y * constant. rate-tile. geth ()/2); tile. setangle (float) (body. getangle () * 180/math. pi);} body = body. m_next;} conut ++ ;}

In the drawing code, draw a background image and a graph in the physical world.

For how to traverse and draw objects in the physical world, box2d also provides us with a method, body = World. getbodylist (); gets the first body and then points it back to the next one.

In the logic code, the processing of the physical logic, in this simple example, is just a constant acquisition of the coordinate angles and collisions of objects in the physical world simulation.

World. Step (constant. steptime, constant. iterations); first, simulate the world, and then obtain the coordinate angle through iteration.

The simplest example is complete.

Here are several constants and variables involved:

Time Step and number of iterations constant. steptime, and constant. iterations (here I save it in the constant class ).

Time and simulation frequency, that is, the number of simulation times in one second (generally 1f/60f), and then the number of iterations (usually 10f). I understand this, that is, the number of times the object state is calculated in one time step. The higher the performance, the more accurate the data is.

Pixel-meter ratio. Constant. rate. that is, the ratio of the screen to the real physical world (30 according to the general settings .) how can this be understood? For example, if you want to draw an object in the middle of the screen (point X and Y of the object are the center of the screen ), then, the coordinates you input are the average screen length and the average width. Press X. the input parameters are 240, 400, and then the physical world determines the object. If there is no proportion, the border of the entire physical world has been defined as AABB. lowerbound = new vec2 (-100,-100 );
AABB. upperbound = new vec2 (100,100 );

The left side of the object to be placed in the physical world is (240 + width, 400 + width ). That is to say, the object directly crosses the boundary. It's not on Earth, it's on Mars. That's simple.

You don't have to worry about it. It's okay to try it several times. The specific value will be modified based on your personal situation.

The following is a small example of object dropping:

Demo address:

Http://download.csdn.net/detail/nono_love_lilith/4130991

By the way, you can also provide the two documents as needed, because downloading this document from Baidu Library may require points, but you cannot download it.

Http://download.csdn.net/detail/nono_love_lilith/4131004

Related Article

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.