Wiki

Clone wiki

agtools / Tutorial 3b - Basic Animation

Outline:

ts3b.png

The purpose of this sample is to turn a static sprite into a grid of animating sprites. It will also introduce the EMSPR sprite format.

Updating the Mainloop

Changes from tutorial 3a are minimal. We're going to swap the asset from IMSPR to EMSPR format, which is faster, at the expense of some memory. IMSPR is the most general purpose format, but also the slowest. EMSPR is a better choice most of the time.

        sprite_asset.load("spinner.ems");

We also need to change the state machine initialisation for EMSPR format drawing instead.

        AGT_BLiT_EMSprInit();

Same goes for the sprite draw function - IMSpr??? becomes EMSpr???.

We're also going to animate the sprite - which is easy. We just change the 'frame' parameter value from 0 to an incrementing variable. We have 8 animation frames in the .ems, so our valid frame range is 0-7.

        AGT_BLiT_EMSprDrawClipped
        (
            /*context=*/&drawcontext,
            /*asset=*/sprite_asset.get(), 
            /*frame=*/((animation_time >> 2) + num) & 7, // careful to keep inside range 0-7
            /*worldpos=*/160 + xo, 120 + yo
        );

In this example we use an always-incrementing animation_time counter. This is divided by 4 (shifted>>2) and masked with 7 (or modulo-8). We get the repeating sequence 0-7. We can adjust the animation speed by changing the shift amount.

This is easy for frame counts which are powers-of-2. For odd frame counts, tables or other tricks are used to bounce or loop the animation.

We have also offset the x,y position of each sprite in the grid, based on the loop count for the sprite drawing. The next example will use a different layout but the usage is the same.

caution:

If you pass a frame number outside of the range provided by the sprite asset, the engine will crash or hang. There is a debug build setting to catch these errors: AGT_CONFIG_SAFETY_CHECKS and faults will report the affected entity and frame number to the console.

If the asset file is not found, the error may not be handled and again you'll get a crash. Once again, a debug check will be added for this case since it is easy to do.

Updated