带有游戏循环的JavaScript Smooth Animation

时间:2012-08-05 20:29:19

标签: javascript animation html5-canvas game-physics

我已将游戏循环简化为仅在屏幕上移动的框Click Here。由于某种原因,盒子似乎没有顺利移动。我做了video of it here

游戏循环的调用如下:

var game = function( ) {
    var now = Date.now( );
    var delta = now - then;

    update( delta / 1000 );
    draw( );

    then = now;
};

setInterval( game, 1000 / 50 );

我尝试将draw调用与主游戏循环分开并将它们放入requestAnimationFrame,但问题仍然存在。我看了一堆似乎运行顺畅的教程。我甚至尝试使用fixed time-step game loop,但这让我的游戏无法快速运行。

如何改进上述逻辑,可能会使用requestAnimationFrame并为deltaTime来电维护update

2 个答案:

答案 0 :(得分:3)

我相信在使用canvas时,你的位置变量应该是整数值,因为它们代表像素,浮点值没有意义。如果你打开控制台并输入sceneManager.currentScene.GameplayLayer.ball.position.x,那么你会得到一个非常长的小数。我认为对OP的评论表明,有时球移动2px而不是1px可能会出现问题。更新位置时,最终会得到一个浮点值。

我相信它有时会向下舍入到下一个最高像素位置,有时会下降。我会试着像这样采取地板或天花板:

this.position.x += Math.floor(this.speed * 100 * deltaTime * Math.cos(directionInRadians));
this.position.y += Math.floor(this.speed * 100 * deltaTime * Math.sin(directionInRadians));

我会做出这两个变化,看看它是如何表现的。

编辑:因为您编辑了您的问题以简化逻辑。我可以建议一些尝试,这是使用我创建的这个我一直使用的Clock对象。它给了我流畅的动画,而且相当简单。它基于clock that Three.JS uses,所以你可能也想检查一下。即使你想使用你自己的代码,你至少可以尝试这个现成的解决方案,看看它是否给你相同的结果。它似乎对我来说很好。此外,您尝试使用垫片,因此您在游戏功能中的调用应为requestAnimFrame(game);

var Clock = function () {

    /** Member startTime will remain fixed at its integer
        millisecond value returned by Date.now(). Will always
        be equal to the time the clock was started */
    this.startTime = Date.now();

    /** Member ms is updated by tick() to a integer value reprsenting 
        the number of milliseconds between the epoch (January 1, 1970)
        and the current date and time of the system. */
    this.ms = this.startTime;
    this.last = this.startTime;  /** millis at last call to tick() */
    this.time = 0;               /** ms in floating point seconds not millis */

    /** Member dt is updated by tick() to an integer value representing
        the number of milliseconds since the last call to tick(). */
    this.dt = 0;
    this.delta = 0; /** dt in floating point seconds not millis */

    /** Member fps is updated by tick() to a floating point value representing
        frames per second, updated and averaged approximately once per second */
    this.fps = 0.0;

    /** Member frameCount is updated to an integer value representing the
        total number of calls to tick() since the clock was created. */
    this.frameCount = 0;

    /** The frameCounter member is a flag you can turn off if you don't need to
        calculate the frameCount or do the average FPS calculation every second */
    this.frameCounter = true;

    /** Private globals needed to calculcate/average fps over eachs second */
    var timeToUpdate = 0;
    var framesToUpdate = 0;

    /************************************************************************************
        The tick() method updates ALL the Clock members, which should only
        be read from and never written to manually. It is recommended that
        tick() is called from a callback loop using requestAnimationFrame

        Learn more: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    *************************************************************************************/
    this.tick = function () {
        /** This is a new frame with it's very own unique number */

        if (this.frameCounter) this.frameCount++;

        /** Set the private currentTime variable */
        this.ms = Date.now();

        /** Update time delta and immediately set last time to
            be as accurate as possible in our timings. */
        this.dt = this.ms - this.last;
        this.last = this.ms;

        /** Calculate floating-point delta and increment time member */
        this.delta = 0.001 * this.dt;
        this.time += this.delta;

        /** Calculate private temp variables for fps calculation */
        if (this.frameCounter) {
            timeToUpdate += this.dt;
            framesToUpdate++;
            if (timeToUpdate > 1000) {
                this.fps = Math.round((framesToUpdate * 1000) / timeToUpdate);
                framesToUpdate = 0;
                timeToUpdate = 0;
            }
        }
    }
}

如果您使用此对象,那么您需要做的就是在初始化函数中创建一个新的时钟对象,如clock = new Clock();。然后在每个动画调用中调用clock.tick()。然后,您可以访问成员clock.deltaclock.time,这将为您提供以秒为单位的浮点值的增量和时间。 clock.dtclock.ms会以毫秒为单位给出与整数相同的内容。您还可以使用clock.fps访问fps,也可以通过设置clock.frameCounter = false来停用它。

答案 1 :(得分:1)

使用three.js时钟平滑我的动画。我强烈推荐它。那里还有很多其他好的代码。