There are three options when it comes to animating a sprite. These are:
In this example we’re going to examine the third option and see how to use a texture atlas.
This example program relies on a single image named "mole.png". This single image contains all of our animation frames bundled together. Here's what it looks like:
The process involved is as follows:
The animation image we are using in this example has all of the individual frames contained in this one image. It is treated just like any other image when it comes to loading:
LoadImage ( 1, "mole.png" )
If you examine this image in an image viewer you will notice how there are 11 individual mole frames. Later on we’ll tell AppGameKit Studio to only display one of these frames at a time.
With our animation image already loaded it’s now time to create our sprite. An ID number of 1 is used for the sprite, followed by another 1 to indicate that this sprite uses image 1:
CreateSprite ( 1, 1 ) SetSpritePosition ( 1, 125, 200 )
If you were to run the application at this point all of image 1 would be displayed. To ensure only specific frames are displayed we call the command SetSpriteAnimation. This has several parameters:
Our image has 11 frames of animation and each one is of dimensions 82 x 88, therefore the call to SetSpriteAnimation should be:
SetSpriteAnimation ( 1, 82, 88, 11 )
After making this call AppGameKit Studio knows enough information about the texture atlas, and it can display each frame individually.
Our sprite now has a texture atlas attached to it, along with vital animation information and we’re now in a position to animate it. All it takes is a call to the command PlaySprite. This command has several parameters:
For our example the ID number is 1, the frame rate is set to 10 (a higher value will make it play faster while a lower value will result in a slower animation), 1 is used to indicate the animation will loop, the start point gets set to frame 1 and finally the end frame is set to frame 11:
PlaySprite ( 1, 10, 1, 1, 11 )
After calling PlaySprite the sprite will continually animate until such time that we choose to stop it.
At this point everything is set up and ready to launch. All that remains is for our main loop to update the screen by making a simple call to Sync, as shown here:
do Sync ( ) loop
Everything is now in place. Here's the final code for our program:
SetVirtualResolution ( 320, 480 )
CreateSprite ( LoadImage ( "background.jpg" ) )
LoadImage ( 1, "mole.png" )
CreateSprite ( 1, 1 ) SetSpritePosition ( 1, 125, 200 )
SetSpriteAnimation ( 1, 82, 88, 11 )
PlaySprite ( 1, 10, 1, 1, 11 )
do Sync ( ) loop
Animating sprites using a texture atlas can result in a minimal amount of code and be very efficient. For platforms where speed is of concern it’s advisable to use texture atlases.