code of the Ninja();

// in search of swift, efficient, and invisible code

2012-01-08

Simple Animation System

Hello again, Code Ninjas!

I'm afraid I have been a little too silent and invisible lately. Upheavals in personal life and multiple projects with disappointingly slow progress have kept me from posting since August, which I'm sure one needn't be told is less than ideal.

But now that the silence has been broken, I'd like to show off the animation system I'm using in my Game Maker Sonic engine, AeStHete.

The Problem

You see, Game Maker has the rudiments of an animation system - all you have to do is set the animation speed for an object, and its sprite will step through all its subimages, looping when it reaches the end and even triggering an event when it does so. But there are huge drawbacks to this system, and it's not even powerful enough to be comparable to the animation system used by the original Sonic the Hedgehog, a 16-bit game that's over 20 years old.

The largest drawback by far is the fact that animations can't be frame lists; if you want to show the same subimage more than once during the animation, you're forced to store two copies of it in the sprite, potentially wasting large amounts of memory, increasing load times, and making your sprites harder to work with.

You also have no ability to vary the animation speed on a frame by frame basis, so if you desire a certain frame to be shown for longer than another, you're out of luck, unless - again - you duplicate it in your original sprite.

Alright, so there are workarounds to these problems, using timelines, or scripting, but they are bothersome and time-consuming to put together. It would be really nice if you could just tell your object to play an animation with a simple command that takes as few arguments as possible while still allowing the features that we'd really like.

Fortunately I've devised a way to do this using scripts, but before I go into it I want to complain about another problem with Game Maker's built-in animation that, while terribly obscure, bothers me no end: If you happen to be using the draw_sprite() function (or one its relatives like draw_sprite_ext()) instead of relying on the default draw event, and use image_index as the subimage argument, it is rounded improperly. So if your image_speed is 0.5 and you are expecting each subimage to be shown for 2 steps, you can get an unpleasant surprise: sometimes they'll be shown for 1 step, or 3... yes, on average the speed is correct but it is not stable, and it looks wrong to the eye, especially for flashing animations that require a steady framerate.

The Solution

So let's avoid all these annoyances by writing scripts that handle animation a lot more like a proper video game would.

The first order of business is to set the image_speed of your object to 0, so that Game Maker will not change the image_index on its own. You want to change it manually, by calling a script which we'll name AnimUpdate().

AnimUpdate()

Let's build up the script step by step, explaining the lines as we go.

Instead of image_speed we'll be using our own variable called animSpeed. Unlike image_speed it will not be a factor (i.e. 1 changes the frame each step, 0.5 changes every other step, etc) but the literal number of steps each frame should be shown until it changes. So if you want an animation that changes frame each second, animSpeed should be equal to your room_speed.

Anyway, if animSpeed is zero or below, we'll exit the AnimUpdate() script altogether; This means you can stop an animation in its tracks by setting animSpeed to 0, or even pause and unpause an animation by multiplying animSpeed by -1 (a neat trick).

This code simply decrements the timer; when the timer reaches zero, the frame will change:

Why use "less than or equal to" instead of just "equal to"? That way, if animTimer is already zero when the script is run, the frame will still change correctly rather than breaking the animation. In fact, this means when we start animations we can initialise animTimer at 0, which makes a little more sense than setting it to 1, and can also be used by other code to check if the animation has just been started but has not updated yet. It's just a little nicety.

The frame number is increased. Why use animFrame and not directly increment image_index? It will become clear in time.

Another nicety that isn't strictly necessary, this allows you to run a custom script each time a frame changes; while this will rarely be used, it is incredibly useful in complicated animations. For instance, Sonic might run a script in his walking animation that calculates the animation speed based on his actual walking speed, and sets animSpeed accordingly. The current frame is given as argument0.

This line checks if the animation has "finished", i.e. whether the frame number is equal to (or greater than) the length of the animation. Why check if it's greater than, also? Because if the animScript changes the current animation for some reason, and the new animation is shorter than the old, the animation won't break. This is a one character change, but it prevents the need to check for such eventualities in your animScript.

This line simply returns the frame number to 0, causing the animation to loop. While this is what we want in most cases, wouldn't it be nice if we had a few more options? So let's replace that line with a switch statement that checks a variable called animEnd and does different stuff.

It will loop only if animEnd is 0, which is what we want most often; -1 will stop the animation; -8192 will cause the instance to destroy itself, which is convenient for simple objects like explosions or other effects which should disappear when their animation has finished; and any other value will simply be added to the frame number so you can, for instance, use -2 to loop the final two frames (as Sonic does when tapping his foot in his boredom animation).

(Ideally we would define constants for these values in GM's constants form, e.g. ANIM_LOOP = 0, ANIM_DESTROY = -8192, etc.)

Onward!

Here we simply reset the timer so that it can count down until the next frame change.

Here, we check a variable called animData to see if it's an empty string. If it is, the image_index should be the current frame number, plus an offset value. The offset value allows us to, for example, have a single sprite which contains every image of the player character. By setting the offset to the index of the subimage where the animation you want to play starts, you can have more than one animation per sprite, seriously cutting down the number of sprites needed. This is part of the reason why we didn't increment the image_index directly earlier, but used a custom variable called animFrame. The second part of the reason is in the next line:

This line is only done if animData is not an empty string but contains some data. This data should always be in the format of a string of digits, e.g. "0102030405198042". This is used as a frame list; the real(string_char_at()) is used to get a frame number from the frame list instead of using animFrame itself, which always counts up in sequence. By using a frame list, you can jump around in the sprite at will, or repeat frames as many times as you want.

Now, you'll notice that you are not allowed with this system to have a frame list that contains values greater than 9, so you can only use 10 different subimages for any animation with a frame list supplied. But this is not usually an issue in classic-style games (it never becomes an issue in Sonic, for one), and if needed you can always add an animScript which changes the offset when needed for especially complex animations.

The frame list is also our way to create variable animation speed. It's not perfect, but by repeating subimages you can achieve almost all effects ever needed, and certainly any needed by a Sonic game.

The last line merely closes the if (animTimer<=0) { block we started, and that does it for the AnimUpdate() script.

AnimPlay()

Now we need to write a script called AnimPlay() that will start animations running. It needs to be supplied with several arguments, most of which are optional. This is how all those variables we were using in AnimUpdate, such as animEnd, animScript, and animData get their values.

There are 5 arguments. The first is animData, which should either be a string like "3120" if you want to use a frame list, or a real number like 4 if you just want to specify the length of a sequential animation.

If argument0 is a string, we know you want to use a frame list, so animData is set to equal argument0 (well, only the digits of the string, anyway, to protect from errors in the real() function later on) and animLength is derived from the length of the string.

If argument0 is a real, however, animData is set to be an empty string and the animLength is set to argument0 directly.

The animSpeed (remember, the number of steps each subimage should be shown before changing) is set to argument1, the only other required argument.

Here, the animOffset is set. It will default to 0 if no argument2 is given, so your animation will start from the first subimage of the sprite being used.

The animEnd is set to argument3. Remember this value specifies the behaviour of the animation when it reaches its end. 0, the default, is loop.

The animScript is set to argument4. If no argument4 is given, it will be 0 so no script will bother to run. (Technically, 0 is a valid script index, but chances are - since the first script you ever create in your game project has the 0 index - it won't be a useful animation script. If you wish to modify this, it's a simple enough matter to tweak this and also AnimUpdate() but you're on your own with it, since I prefer the elegance of doing it this way.)

The animTimer is set to 0 so that when AnimUpdate() is called next (preferably in something like the End Step Event) the animation will initialise at the first frame. The animFrame is set to -1; it will be incremented to 0 when the animation starts.

Conclusion

So that's all that it takes to make a reasonably robust animation system with far more power than Game Maker's simple image_speed implementation. You may download the GML scripts from this tutorial here.

As a fun exercise, you can modify this system easily to use a delta value when decrementing the animTimer:

If the delta is a global value, you can slow all animations by any factor simultaneously, allowing you to create all kinds of cool slow-motion effects. Some problems will arise if the delta is greater than 1, but it wouldn't be an exercise if you didn't have to figure out how to solve something on your own. (Don't worry, it's not too difficult.)

I'd explain it all right now, anyway, but I've got to get back to coding my AeStHete engine. Until next time, happy coding!