Game Development Reference
In-Depth Information
The
goalReached
variable is used to keep track of the game's state whether or not
the player has already managed to reach the goal. The
World
class directly relates
to the description at the beginning of this chapter. In the
initPhysics()
method,
we create a new instance of
World
, and store it in the
b2world
variable for later
reference. The constructor of
World
takes an instance of
Vector2
for the world's
simulated gravity, and a second parameter that controls the weather bodies in Box2D
can become inactive. Usually, this flag should be enabled to reduce the CPU load
and in particular to preserve some battery power on mobile devices. In our case, we
create a world with gravity, pulling down objects at 9.81 meters per second squared,
which is the same acceleration that we experience on earth.
Remember to always call the
dispose()
method of World when it is
no longer needed. This is also true for all the Box2D shape classes, for
example,
PolygonShape
and
CircleShape
.
After the Box2D world is created, we loop through the level's list of rocks, and
create the corresponding Box2D bodies that are mapped to the same position and
size as defined in the loaded level. Thus, both worlds, the Box2D one and our level,
will start in a synchronized model state for each rock. Creating bodies for the rocks
is a necessary step because Box2D will have to take each rock into account in its
calculations. Otherwise, the carrot game objects will fall through everything in the
level because there simply is nothing to collide with from Box2D's point of view.
Box2D requires you to use separate definition classes to create new instances of
Body
and
Fixture
, which are named
BodyDef
and
FixtureDef
, respectively. The
instance in the
bodyDef
variable is configured to describe a kinematic body type
whose initial position is set to the same position as the rock instance. After this,
we call the
createBody()
method of
b2world
and pass in the body definition
to create and add the new body at once. The method returns the reference of the
newly created body, which is then stored in the rock instance to activate the Box2D
physics handling, according to the changes we just made in our
update()
method of
AbstractGameObject
.
The created body also needs a shape to allow interaction with other bodies. So, we
create a shape using the
PolygonShape
class and call its
setAsBox()
helper method
to define a rectangle. Shapes cannot be directly attached to bodies; thus, we create
a new instance of the
Fixture
class, bind our shape to it, and eventually attach the
fixture to the body of the rock by calling the
createFixture()
method of the
body
instance. Now, the shape is no longer needed as its information has been processed
in the new fixture. This is why we can safely call the
dispose()
method on the shape
to free the memory that was allocated by this shape.