How to move an object in box2d

Source: Internet
Author: User

 

Recently I have studied box2d, and I have learned about it in general. However, when running the demo of the ball's whereabouts, I found that the moving speed is different from the physical condition, after studying it carefully, I found that there were so many details that I should pay attention. This must be recorded. It will certainly be helpful to those who have the same problems in the future.

 

Physical Model:

A square box with a side length of 1 m is positioned at a height of 20 m, and then freely falls into the body. According to the formula h = gt ^ 2/2, It is 2 s when the data falls to 0 m.

Corresponding to the box2d model:

A positive four-corner shape with a side length of 1 m does not have any damping, placed in the air of 20 m, and then set the downward gravity to 9.8 m/s ^ 2.

 

Note 1: unit conversion

This is the most error-prone place for beginners. Since the distance unit in libgdx is px, but the box2d distance unit is m, make sure that the unit is correct for all the values to be calculated in your program.

Specifically, for example, if my display resolution is 1440px * 900px, then I create a game interface of 200px * 200px, such as new JoglApplication (new DemoGame (), "Demo ", 200,200, false );. It is easy to understand that your entire game interface is of this size, which is in direct proportion to the display resolution.

Then, there will be a camera in the game to see the specific interface content. Here we only consider that the positive projection camera will not zoom in or out of the interface due to the distance ), so what we can see is the new OrthographicCamera (200,200) image of 200px * 200px. This is actually the 1px on the screen that represents the 1px of your monitor. The change in camera size is that 1px in your game is inversely proportional to 1px in the actual display. I think this is the same as the game interface settings.

If I want 10 pixels to represent 1 mscale = 10px/m), then the calculated displacement of each object is 1 MB, and the actor will move 10 pixels. This is the conversion relationship.

NOTE 1: The units in box2d are standard units. For example, the length is m and the weight is kg.

Note 2: The physical computing of box2d is separated from the actor on the screen. Physical data must be synchronized to the actor. However, in Box2DDebugRenderer, You can intuitively view the physical world.

 

NOTE 2: maximum speed limit

At this time, it was a little interesting to move the object. When the world's gravity was added to a great deal, something strange happened. It started to accelerate the movement, and suddenly it turned into a constant speed. After checking the data, we found that box2d limited the displacement of each frame to 2 m/frame, so the maximum moving speed of the object was 120 m/s at the 60Hz update rate. The tragedy is that this restriction is hard coding, which may make the object seem to move continuously. So to increase the speed, we can only increase the number of frames, such as world. step (1/100f, 3, 3); the maximum speed to be improved is 200 Mb/s, but such modification may cause a serious problem, it is to make the time scale of the object displacement different from the actual time. The screen looks different from the human perception.

Note: timestep is the time step, which is an important concept in the animation. Every time the physical world calculates a new position, it is necessary to know how long it will take, this turns discrete time point computation into a continuous animation.

 

NOTE 3: initialization impact

All the above work is done, and no statistics are made on the fall time. After half a day, the system sent a response. The first render had started to calculate the moving of the object and brought the deltaTime into the computation. Because the initialization speed will be slow and the program will not be able to refresh 60Hz, it is too late for me to take that time as the first fall time. So let's simply wake up every object after the first render, and this will get the expected result.

 

 

Attached test code:

 
 
  1. Public class DemoGame implements ApplicationListener {
  2.  
  3. Protected OrthographicCamera camera;
  4. Protected Box2DDebugRenderer renderer; // Tester
  5. Private World;
  6. Private float scale = 10f; // screen zoom ratio, 10 pixels/Meter
  7. Private long start = 0;
  8. Private Body body;
  9. Private boolean isFinished = true;
  10. Private int count = 0;
  11. Private float totalTime = 0;
  12.  
  13. @ Override
  14. Public void create (){
  15. Thread. currentThread (). setPriority (Thread. MAX_PRIORITY );
  16. Camera = new OrthographicCamera (200/scale, 200/scale); // here, to demonstrate the physical world, the field of view is also converted to m
  17. Camera. position. set (100/scale, 100/scale, 0); // the camera's postion is the center of the screen
  18. Renderer = new Box2DDebugRenderer ();
  19. World = new World (new Vector2 (0,-9.8f), true); // general standard gravity field
  20. BodyDef bd = new BodyDef (); // declare object definition
  21. Bd. position. set (10, 20 );
  22. Bd. type = BodyType. DynamicBody;
  23. Body = world. createBody (bd); // creates an object through world
  24. PolygonShape box = new PolygonShape ();
  25. Box. setAsBox (0.5f, 0.5f); // note that the unit is half the side length.
  26. FixtureDef fd = new FixtureDef ();
  27. Fd. shape = box;
  28. Fd. friction = 0;
  29. Fd. restitution = 0;
  30. Fd. density = 1;
  31. Body. createFixture (fd); // assign the shape and density to the object
  32. Body. setLinearDamping (0f); // no linear damping
  33. Body. setAngularDamping (0f); // No rotation Damping
  34. Body. setAwake (false );
  35. }
  36.  
  37. @ Override
  38. Public void render (){
  39. World. step (Gdx. app. getGraphics (). getDeltaTime (), 3, 3 );
  40. If (start = 0 ){
  41. Count = 1;
  42. Start = System. currentTimeMillis ();
  43. System. out. println ("start postion:" + body. getPosition (). y );
  44. Body. setAwake (true); // Let the first frame of the rendering move the object again, so that the time is accurate,
  45. // Otherwise, the first deltaTime has an initialization time, which will make the entire calculation inaccurate.
  46. } Else {
  47. If (isFinished ){
  48. System. out. println ("animation rendering times:" + count ++ );
  49. System. out. println ("object moving speed:" + body. getLinearVelocity (). y );
  50. System. out. println ("---------------------------------");
  51. TotalTime + = Gdx. app. getGraphics (). getDeltaTime ();
  52. }
  53. If (body. getPosition (). y <= 0 & isFinished ){
  54. System. out. println ("actual time difference:" + (System. currentTimeMillis ()-start)/1000f );
  55. System. out. println ("Time Difference in incremental image statistics:" + totalTime );
  56. System. out. println ("end postion:" + body. getPosition (). y );
  57. IsFinished = false;
  58. World. destroyBody (body );
  59. }
  60. }
  61. GL10 gl = Gdx. app. getGraphics (). getGL10 ();
  62. Gl. glClear (GL10.GL _ COLOR_BUFFER_BIT );
  63. Camera. update ();
  64. Camera. apply (gl );
  65. Renderer. render (world, camera. combined );
  66. }
  67. @ Override
  68. Public void dispose (){
  69. Renderer. dispose ();
  70. World. dispose ();
  71. Renderer = null;
  72. World = null;
  73. }
  74. @ Override
  75. Public void pause (){
  76. }
  77.  
  78. @ Override
  79. Public void resize (int width, int height ){
  80. }
  81.  
  82. @ Override
  83. Public void resume (){
  84. }
  85. }

 

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.