Tuesday, 13 December 2011

JBox2D Tutorial : JBox2D World

From today I am starting JBox2D tutorial series. In each post I will explain few features of the JBox2D.  I will try to keep each post small and simple.

In today’s post I will explain how to create the JBox2D world.

What is a JBox2D?

JBox2D is a java based physics engine API for game development. This is a java port for a very popular C++ library called Box2d.  This can be used in games to move objects in a natural way. JBox2D works well with moving objects between 0.1 to 1 meters size.  Jbox2D doesn’t have its own UI. It creates an invisible object. We need to attach UI components to these invisible objects. 
Creating the JBox2D World

To write any JBox2D program, the first thing we need to do is to create a JBox2d world. World is a collection of bodies, fixtures and constraints. Memory, objects and simulations are managed by the World.

Following is a code snippet for creating a JBox2D World

Vec2 gravity = new Vec2(0.0f, -10.0f);
boolean doSleep = true;
World world = new World(gravity, doSleep);

As you can see in above code snippet, two parameters (Gravity and the doSleep) are passed to the World objects constructor. 

Gravity – gravity is an attraction of the mass for bodies present in the World. As you can see in above snippet, Vec2 object is used for defining the gravity. The first parameter defines the horizontal gravity and second parameter defines the vertical gravity.  In most cases first parameter is set to zero as requirement for horizontal gravity is very rare. If negative value is set for the second parameter then bodies are attracted downwards. And if positive value is set for the second parameter then bodies are attracted upwards.  In most cases negative value is set to the second parameter

doSleep – If doSleep is set to true, JBox2d world will allow bodies to sleep when they come to rest. The sleeping bodies are not part of simulations; it means better performance as body simulations are expensive. In most cases this parameter should be set to true.

I have created small application to understand gravity behavior.  This is the sample video.

Soon I will provide launch URL for this application.  

                                                                              Creating an object body>>


  1. Best jbox2D tutorial on the web.

    Any chance of doing a post on different types of

  2. I know I am kinda late, but I just started to study jBox2D and there aren´t any good tutorials on the web, except yours, is there any chance u have made some other tutorials with jBox2D engine?

  3. Thank you for this tutorial. It is most helpful!

  4. What is Utils class and where can i find it?
    Can not find it in imports...

  5. Thanks for putting effort in creating this tutorial series


There was an error in this gadget