Game Development Reference
In-Depth Information
Listing 9-12. Squirrel.java, the Squirrel Class
package
com.badlogic.androidgames.jumper;
import
com.badlogic.androidgames.framework.DynamicGameObject;
public class
Squirrel
extends
DynamicGameObject {
public static final float
SQUIRREL
_
WIDTH
= 1;
public static final float
SQUIRREL
_
HEIGHT
= 0.6f;
public static final float
SQUIRREL
_
VELOCITY
= 3f;
float
stateTime = 0;
public
Squirrel(
float
x,
float
y) {
super
(x, y, SQUIRREL_WIDTH, SQUIRREL_HEIGHT);
velocity.set(
SQUIRREL
_
VELOCITY
, 0);
}
public void
update(
float
deltaTime) {
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
bounds.lowerLeft.set(position).sub(
SQUIRREL
_
WIDTH
/ 2,
SQUIRREL
_
HEIGHT
/ 2);
if
if(position.x <
SQUIRREL
_
WIDTH
/ 2 ) {
position.x =
SQUIRREL
_
WIDTH
/ 2;
velocity.x =
SQUIRREL
_
VELOCITY
;
}
if
if(position.x > World.
WORLD
_
WIDTH
-
SQUIRREL
_
WIDTH
/ 2) {
position.x = World.
WORLD
_
WIDTH
-
SQUIRREL
_
WIDTH
/ 2;
velocity.x = -
SQUIRREL
_
VELOCITY
;
}
stateTime += deltaTime;
}
}
Squirrels are moving objects, so we let the class derive from
DynamicGameObject
, which gives us
a velocity vector and an acceleration vector as well. The first thing we do is define a squirrel's
size, as well as its velocity. Since a squirrel is animated, we also keep track of its state time.
A squirrel has a single state, like a coin: moving horizontally. Whether it moves to the left or
right can be decided based on the velocity vector's x component, so we don't need to store a
separate state member for that.
In the constructor, we call the superclass's constructor with the initial position and size of the
squirrel. We also set the velocity vector to (
SQUIRREL_VELOCITY
,0). All squirrels will thus move to
the right in the beginning.
The
update()
method updates the position and bounding shape of the squirrel based on the
velocity and delta time. It's our standard Euler integration step, which we talked about and used
a lot in Chapter 8. We also check whether the squirrel hit the left or right edge of the world.
If that's the case, we simply invert its velocity vector so that it starts moving in the opposite
direction. Our world's width is fixed at a value of 10 meters, as discussed earlier. The last thing