I am working on a small mario game.
But I can't figure out how to anime sprites. As per example, I have a running mario.gif file (mario is not runnning in the gif)
Click here for the mario picture.
The picture is 60 x 20 pixels. At the moment, this is my code.
class Character {
public y_: number;
public x_: number;
public nFrames: number = 30;
constructor(public _x: number, public _y: number) {
this._x = _x;
this._y = _y;
};
sprite: HTMLImageElement;
setSpriteUrl(input: string) : void {
this.sprite = new Image();
this.sprite.src = input;
}
drawSprite(): void {
ctx.save();
ctx.beginPath();
ctx.drawImage(this.sprite, 0, 0, 15, 20, this._x, this._y, 20, 20);
ctx.restore;
}
}
and after that
var mario = new Character(40, 50);
mario.setSpriteUrl("graphics/mario/small/Running-mario.gif");
the width of the picture is 60 pixels and there are 4 running images of mario. The height of the picture is also 20 pixels.
60/4 = 15.
ctx.drawImage(this.sprite, 0, 0, 15, 20, this._x, this._y, 20, 20);
This would make me think that it I can go from 15 to 30 and it would select the next mario image. Instead it gives me 2 running mario's from the picture.
How does it work? How can select every running stage of mario?
If that is done, should the sprite be animated with a for loop and a timer to do that? To me it doesn't seem like the best practice.. Since I have more sprites to animate then only mario and running.