Animation

This example covers background tile animation. It's not interactive, but look at how much more interesting it is compared to a static tile map. Even with a player and enemies moving around the screen, your game will benefit from having background animations.

There are a few ways you can do animations. You probably noticed that all the grass in this example is moving the same way. This is because there's only one animation in use here being accessed by every grass filled tile space. The animation object looks like this:

function Animation(values_, interval_) {
	this.count = 0;
	this.index = 0;
	this.interval = interval_;
	this.value = values_[0];
	this.values = values_;
}

You could probably guess how it works just by looking at it, but some of the naming conventions I used aren't so straight forward out of context. The values_ parameter takes an array of tile values that looks like this:

[ 1, 2, 3, 2 ]

The values in the array correspond to tiles in the tile sheet. Think of them as frames in the animation, which in this case is four frames long.

The interval_ parameter is how long to wait before displaying the next frame in the animation. On each game cycle or logic update, the animation's count value increases. When it matches the interval, the frame index increases and the frame value is set to the next value in the animation. In code it looks like this:

update : function() {
	this.count++;

	if (this.count == this.interval) {
		this.count = 0;
		this.index = this.index < this.values.length-1 ? this.index + 1 : 0;
		this.value = this.values[this.index];
	}
}

This function is called on every update and effectively creates fluid animation. To put it in a different perspective, think of the index as the play head, the values array as the animation frames and the interval as the frame rate. The only slightly complicated line in this block of code is where the index is set. All it does is first check to see if the index will go out of the range of the values array. If it's greater than the available number of frames in the values array, it resets to zero, thus looping the animation. Otherwise it increases by one, thus moving the animation forward.

And that's it! It's pretty simple. Animating player movement has a lot more to it, but you can use the same animation object. Background animations are important because they add a whole new level of immersion to your game. They're simple enough to add in, too. This example only uses 230 lines of code, and half of that is comments and blank lines. For a more in depth explanation of the program, take a look at the fully commented source!


Control Source #