Animating sprites in HTML5 canvas
- by fnx
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... :)