Game Development Reference
In-Depth Information
Letting it rain carrots
We will now focus on the implementation details, where we actually make use
of Box2D in Canyon Bunny. Remember that we have created our own simple
physics simulation for the game objects before. We do not want to replace this
implementation but in fact allow the use of either one of them as it suits our needs.
In other words, we want to keep the existing implementation that is doing collision
detection and physics for the game objects, and just add a coexisting alternative that
uses Box2D.
Add the following import line to the AbstractGameObject class:
import com.badlogic.gdx.physics.box2d.Body;
After this, add the following line to the same class:
public Body body;
The (rigid) Body class directly relates to what we have discussed at the beginning
of this chapter. Next, make the following changes to the update() method in the
same class:
public void update (float deltaTime) {
if (body == null) {
updateMotionX(deltaTime);
updateMotionY(deltaTime);
// Move to the new position
position.x += velocity.x * deltaTime;
position.y += velocity.y * deltaTime;
} else {
position.set(body.getPosition());
rotation = body.getAngle() * MathUtils.radiansToDegrees;
}
}
The idea here is that each game object will be using our simple physics as long as
there is no Box2D body defined in the body variable. Otherwise, the current position
and angle of rotation is simply taken from the body and applied to the game object to
reflect the state of Box2D's calculations. In conclusion, this means that we have given
full control to Box2D over the movement parameters for these game objects.
 
Search WWH ::




Custom Search