I've been tackling the development of a small Mario game lately.
However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in the gif).
Check out the Mario image here.
The image size is 60 x 20 pixels. Here's my current code snippet:
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;
}
}
Then follows this part:
var mario = new Character(40, 50);
mario.setSpriteUrl("graphics/mario/small/Running-mario.gif");
The picture width is 60 pixels with 4 running images of Mario. The height remains 20 pixels.
Hence, 60/4 = 15.
ctx.drawImage(this.sprite, 0, 0, 15, 20, this._x, this._y, 20, 20);
This makes me believe that I could advance from 15 to 30 to select the next stage of Mario running. However, instead of that, it displays 2 running Marios from the same image.
How does this functionality work? How can every running phase of Mario be selected?
Once that's resolved, should the sprite be animated using a for loop and timer? It doesn't seem like the most optimal approach to me, especially considering there are more sprites than just Mario's running animation.