为什么这个基本的Canvas动画不流畅?

时间:2016-09-10 09:19:34

标签: javascript animation canvas html5-canvas craftyjs

我在动画循环中唯一要做的就是更新x和y坐标,但圆圈仍然没有像它应该的那样平滑。 This is the fiddle。我正在使用CraftyJS为圆圈制作动画。以下是执行动画的代码:

.bind("EnterFrame", function (eventData) {
     this.x += this.xDirection;
     this.y += this.yDirection;
     if (this.x < 0) this.xDirection *= -1;
     if (this.y < 0) this.yDirection *= -1;
     if (this.x > (0.96*gWidth)) this.xDirection *= -1;
     if (this.y > (0.96*gHeight)) this.yDirection *= -1;
});

其余的计算只进行一次,我不认为只是一堆乘法应该使动画滞后。任何有关如何使动画流畅的帮助将不胜感激。

我之前没有提及xDirection等于0.005*gWidthyDirection等于0.005*gHeight。如果gWidth600,则球仍在移动3px。真的那么快吗?我不想指定宽度(以像素为单位)(gWidth是屏幕大小)因为那时游戏玩法在不同设备上会有所不同。有没有办法在保持动画流畅的同时快速移动圆圈?

1 个答案:

答案 0 :(得分:0)

从“固定”步进式更改为“可变”步进式对我来说很平滑。 在Crafty.init之后,调用Crafty.timer.steptype()

const _step = 20;
Crafty.init(gWidth, gHeight, document.getElementById('game'));
Crafty.timer.steptype('variable', _step);
// ...

您可能还想更新EnterFrame,以考虑自上一帧以来经过的时间:

.bind("EnterFrame", function (eventData) {
    let dt = eventData.dt;
    this.x += this.xDirection * dt / _step;
    this.y += this.yDirection * dt / _step;
    // ...
相关问题