Animating sprites in HTML5 canvas

Posted by fnx on Game Development See other posts from Game Development or by fnx
Published on 2012-12-02T23:34:29Z Indexed on 2012/12/03 5:54 UTC
Read the original article Hit count: 222

Filed under:
|

I'm creating a 2D platformer game with HTML5 canvas and javascript. I'm having a bit of a struggle with animations. Currently I animate by getting preloaded images from an array, and the code is really simple, in player.update() I call a function that does this:

var animLength = this.animations[id].length;
this.counter++;
this.counter %= 3;
if (this.counter == 2) this.spriteCounter++;
this.spriteCounter %= animLength;
return this.animations[id][this.spriteCounter];

There are a couple of problems with this one: When the player does 2 actions that require animating at the same time, animation speed doubles. Apparently this.counter++ is working twice at the same time. I imagine that if I start animating multiple sprites with this, the animation speed will multiply by the amount of sprites. Other issue is that I couldn't make the animation run only once instead of looping while key is held down.

Someone told me that I should create a function Animation(animation id, isLooped boolean) and the use something like player.sprite = new Animation("explode", false) but I don't know how to make it work.

Yes I'm a noob... :)

© Game Development or respective owner

Related posts about html5

Related posts about canvas