Game Development Reference
In-Depth Information
We can easily do this with our
TextureRegion
and
SpriteBatcher
classes. Usually, we'd not only
have a single animation, like the one in Figure
8-25
, but many more in a single atlas. Besides
the walk animation, we could have a jump animation, an attack animation, and so on. For each
animation, we need to know the frame duration, which tells us how long to keep using a single
keyframe of the animation before switching to the next frame.
The Animation Class
Let us define the requirements for an
Animation
class, which stores the data for a single
animation, such as the walk animation in Figure
8-25
:
ï?®
Animation
holds a number of
TextureRegion
s, which store where each
keyframe is located in the texture atlas. The order of the
TextureRegion
s is
the same as that used for playing back the animation.
An
ï?®
Animation
also stores the frame duration, which has to pass before we
switch to the next frame.
The
ï?®
Animation
should provide us with a method to which we pass the time
we've been in the state that the
Animation
represents (for example, walking
left), and that will return the appropriate
TextureRegion
. The method should
take into consideration whether we want the
Animation
to loop or to stay at
the last frame when the end is reached.
This last bullet point is important because it allows us to store a single
Animation
instance to
be used by multiple objects in our world. An object just keeps track of its current state, that is,
whether it is walking, shooting, or jumping, and how long it has been in that state. When we
render this object, we use the state to select the animation we want to play back and the state
time to get the correct
TextureRegion
from the
Animation
. Listing 8-19 shows the code of our
new
Animation
class.
The
Listing 8-19. Animation.java, a Simple Animation Class
package
com.badlogic.androidgames.framework.gl;
public class
Animation {
public static final int
ANIMATION_LOOPING
= 0;
public static final int
ANIMATION_NONLOOPING
= 1;
final
TextureRegion[] keyFrames;
final float
frameDuration;
public
Animation(
float
frameDuration, TextureRegion ... keyFrames) {
this
.frameDuration = frameDuration;
this
.keyFrames = keyFrames;
}
public
TextureRegion getKeyFrame(
float
stateTime,
int
mode) {
int
frameNumber = (
int
)(stateTime / frameDuration);