Java Reference
In-Depth Information
Tiles within a
TiledLayer
can be animated; that is, they can rotate through differ-
ent tiles in succession—for example, when the illusion of moving water is desired.
To do this, you need only denote each of the animated tiles as animated using the
createAnimatedTile
method and passing the index of the animated tile frame. The
createAnimatedTile
method returns a
negative
number, which you use when setting
cell values using
setCell
. In turn, you can change all animated tiles of a given index to
a different animated tile by invoking the
setAnimatedTile
method and passing the
index of the original tiles to change and the index that they should be changed to.
Producing Animations
While the
TiledLayer
class is appropriate for creating large visible areas (perhaps with
rudimentary animation within the visible area), the
Sprite
class is best used for small
objects consisting of one or more bitmaps. You can animate
Sprite
objects by cycling
through separate animation frames. Like the
TiledLayer
, these frames are given to a
Sprite
as a single
Image
object consisting of multiple frames, each with a constant
width and height. Figure 8-3(a) shows the three frames of an animated butterfly, while
Figure 8-3(b) shows one way you can composite those frames into a three-frame ani-
mation's source
Image
.
Figure 8-3.
As shown in (a), three frames make up the animation; in (b), these are combined
into a single
Image
instance to pass to the
Sprite
class.
â–
Tip
Transparency in the source
Image
is indicated in the usual way, such as by using the alpha channel
of a PNG file.
Each frame is assigned a unique index; unlike tiles for a
TileLayer
, the
Sprite
class
counts frames starting at
0
. Subsequent indexes are assigned from left to right and top to
bottom. For example, to create a
Sprite
instance corresponding to the animation consist-
ing of the frames in Figure 8-3(a), you might write the code shown in Listing 8-7.