在画布中动画精灵帧
Animating sprite frames in canvas
我正在制作一款带有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是一个毫秒值)。根据你的帧率和动画,这可能看起来很不稳定,但它不依赖于持久计数器。
相关文章:
- 打字精灵动画
- 在EaselJS中设置精灵表动画时出现问题
- 如何使用Javascript创建带有精灵表的动画按钮
- 动画与精灵HTML5
- 使用HTML5和JavaScript创建精灵动画
- 在JS中缓和精灵动画
- GameClosure:精灵动画
- 使用 SpriteStage (WebGL) 创建 EaselJS 精灵动画
- 如何确定动画精灵何时到达某个点
- 如何在 javascript 中减慢我的精灵表动画
- EaselJS 精灵表动画在画布上不可见,但没有错误
- 游戏中的JavaScript精灵动画
- 仅在鼠标悬停时播放精灵动画
- 控制精灵动画速度
- CS精灵动画
- 如何在精灵上更改精灵动画的速度
- 如何让这些精灵动画在Firefox中工作
- 预加载程序与精灵动画
- 我如何用不同的按钮制作不同的精灵动画?(HTML / CSS)
- 同时运行多个Javascript png精灵动画