Game Development Reference
In-Depth Information
if
(mode ==
ANIMATION_NONLOOPING
) {
frameNumber = Math.
min
(keyFrames.length-1, frameNumber);
}
else
{
frameNumber = frameNumber % keyFrames.length;
}
return
keyFrames[frameNumber];
}
}
First, we define two constants to be used with the
getKeyFrame()
method. The first one says the
animation should be looping, and the second one says that it should stop at the last frame.
Next, we define two members: an array holding the
TextureRegion
s, and a float storing the
frame duration.
We pass the frame duration and the
TextureRegion
s that hold the keyframes to the constructor,
which simply stores them. We can make a defensive copy of the
keyFrames
array, but that would
allocate a new object, which would make the garbage collector a little mad.
The interesting piece is the
getKeyFrame()
method. We pass in the time that the object has been
in the state that the animation represents, as well as the mode, either
Animation.ANIMATION_
LOOPING
or
Animation.NON_LOOPING
. We calculate how many frames have already been played for
the given state, based on the
stateTime
. If the animation shouldn't be looping, we simply clamp
the
frameNumber
to the last element in the
TextureRegion
array. Otherwise, we take the modulus,
which will automatically create the looping effect we desire (for example, 4 % 3 = 1). All that's left
is returning the proper
TextureRegion
.
An Example
This section shows how to create an example called
AnimationTest
, with a corresponding
screen called
AnimationScreen
. As always, only the screen itself will be discussed.
We want to render a number of cavemen, all walking to the left. Our world will be the same size
as our view frustum, which has the size 4.8×3.2 m. (This is arbitrary; we could use any size.) A
caveman is a
DynamicGameObject
with a size of 1×1 m. We will derive from
DynamicGameObject
and create a new class called
Caveman
, which will store an additional member that keeps track
of how long the caveman has been walking. Each caveman will move 0.5 m/s, either to the
left or to the right. Add an
update()
method to the
Caveman
class to update the caveman's
position, based on the delta time and his velocity. If a caveman reaches the left or right edge
of the world, we set him to the other side of the world. We use the image in Figure
8-25
and
create
TextureRegion
instances and an
Animation
instance, accordingly. For rendering, we use a
Camera2D
instance and a
SpriteBatcher
because they are fancy. Listing 8-20 shows the code of
the
Caveman
class.
Listing 8-20. Excerpt from AnimationTest.java; Showing the Inner Caveman Class
static final float
WORLD_WIDTH
= 4.8f;
static final float
WORLD_HEIGHT
= 3.2f;
static class
Caveman
extends
DynamicGameObject {
public float
walkingTime = 0;