简体   繁体   English

在画布中动画精灵帧

[英]Animating sprite frames in canvas

I'm making a small platform game with the canvas element and I'm having trouble working out the best way to use sprites. 我正在使用canvas元素制作一个小型平台游戏,但我在寻找使用Sprite的最佳方法时遇到了麻烦。

Canvas doesn't support animated GIFs, so I can't do that, so instead I made a film strip for my animated sprites to give the illusion that a character is moving. Canvas不支持动画GIF,所以我不能这样做,所以我为动画精灵制作了一个电影胶片,给人以角色正在移动的错觉。 Like this: http://i.imgur.com/wDX5R.png 像这样: http : //i.imgur.com/wDX5R.png

Here's the relevant code: 以下是相关代码:

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();

As you can see, I'm defining the idle sprite and also its frame width and frame count. 如您所见,我正在定义空闲子画面及其帧宽度和帧数。 Then in my draw method, I'm using those properties to tell the drawImage method what frame to draw. 然后在我的draw方法中,我使用这些属性来告诉drawImage方法绘制什么帧。 Everything works fine, but I'm unhappy with the frameCount variable defined before the draw method. 一切正常,但是我对在draw方法之前定义的frameCount变量不满意。 It seems... hacky and ugly. 看来...骇人又丑陋。 Would there be a way that people know of to achieve the same effect without keeping track of the frames outside the draw method? 人们会知道有一种方法可以在不跟踪draw方法外部的框架的情况下达到相同的效果吗? Or even a better alternative to drawing animated sprites to canvas would be good. 甚至可以用更好的替代方法将动画精灵绘制到画布上。

Thanks. 谢谢。

You could select the frame depending on some fraction of the current time, eg 您可以根据当前时间的一部分选择帧,例如

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);
}

That will give you animation with a period of one second (the 1000 is a millisecond value). 这将为您提供一秒的动画时间(1000是毫秒值)。 Depending on your frame rate and animation this might look jerky, but it doesn't rely on persistent counters. 根据您的帧频和动画,这可能看起来有些生涩,但它并不依赖于持久计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM