在画布中动画精灵帧

Animating sprite frames in canvas

本文关键字:精灵 动画 布中      更新时间:2023-09-26

我正在制作一款带有canvas元素的小型平台游戏,但我在寻找使用精灵的最佳方法时遇到了麻烦。

Canvas不支持动图,所以我不能这样做,所以我为我的动画精灵制作了一个电影带,给人一种角色在移动的错觉。像这样:https://i.stack.imgur.com/FUuHg.png

相关代码如下:

function player() {
    this.idleSprite = new Image();
    this.idleSprite.src = "/game/images/idleSprite.png";
    this.idleSprite.frameWidth = 28;
    this.idleSprite.frameHeight = 40;
    this.idleSprite.frameCount = 12;
    this.runningSprite = new Image();
    this.runningSprite.src = "/game/images/runningSprite.png";
    this.runningSprite.frameWidth = 34;
    this.update = function() {
    }
    var frameCount = 1;
    this.draw = function() {
        c.drawImage(this.idleSprite, this.idleSprite.frameWidth * frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
        if(frameCount < this.idleSprite.frameCount - 1) { frameCount++; } else { frameCount = 0; }
    }
}
var player = new player();

正如你所看到的,我正在定义空闲精灵以及它的帧宽和帧数。然后在我的draw方法中,我用这些属性告诉drawImage方法画哪一帧。一切工作正常,但我不满意的frameCount变量之前定义的绘制方法。似乎……又黑又丑。是否有一种方法,人们知道,以达到相同的效果,而不保持跟踪框架以外的绘制方法?或者甚至是一个更好的选择,绘制动画精灵画布将是不错的。

谢谢。

你可以根据当前时间的一部分来选择帧,例如

this.draw = function() {
    var fc = this.idleSprite.frameCount;
    var currentFrame = 0 | (((new Date()).getTime()) * (fc/1000)) % fc;
    c.drawImage(this.idleSprite, this.idleSprite.frameWidth * currentFrame, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
}

这将给你一个周期为一秒的动画(1000是一个毫秒值)。根据你的帧率和动画,这可能看起来很不稳定,但它不依赖于持久计数器。