Game Development Reference
In-Depth Information
last part, % frameNum is there to restart the animation when it reaches beyond its last
frame. So in the case where 2.3 seconds have passed, we have the following result:
2.3 * 8 = 18.4
We do not have a 19th frame to show, so we show the frame which corresponds to that in
our local scale [0…7]. In this case:
18 / 8 = 2 (and 2 remainder)
Since the % operator takes the remainder of a division, we are left to show the frame with
the index two, which is the third frame. (We start counting from zero as programmers, re-
member?)
The last line of the code sets the texture rectangle to the current frame. The process is
quite straightforward—since we only have frames on the x axis, we do not need to worry
about the y coordinate of the rectangle, and so we will set it to zero. The x is computed by
animFrame * spriteSize.x , which multiplies the current frame by the width of
the frame. In the case, the current frame is two and the frame's width is 32, so we get:
2 * 32 = 64
Here is what the texture rectangle will look like:
The last thing we need to do is render the sprite inside the render frame and we are done.
If everything goes smoothly, we should have a rotating crystal on the screen with eight
frames. With this technique, we can animate sprites of all kinds no matter how many
frames they have or how long the animation is. There are problems with the current ap-
proach though—the code looks messy, and it is only useful for a single animation. What if
we want multiple animations for a sprite (rotating the crystal in a vertical direction as
well), and we want to be able to switch between them? Currently, we would have to du-
plicate all our code for each animation and each animated sprite. In the next section, we
Search WWH ::




Custom Search