javascript - 随着游戏的进行,游戏循环出现滞后

标签 javascript jquery performance optimization game-loop

这是我在游戏循环方面的小尝试。 Here is the Demo 。 (继续单击灰色区域即可启动)。

问题是,点击一段时间后,游戏动画会变得断断续续,并达到定格动画的程度,之后我需要关闭浏览器选项卡。

这里肯定有一些我遗漏的东西。可能是游戏空闲时需要插入的延迟之类的东西。
这是我一直在研究的代码:
HTML

<div class="container">
    <div class="player"></div>
</div>

JavaScript

var player = {
    height: 0,
    width: 0,
    image: "",
    score: 0,
    highestScore: 0
};
var newColor=null;

/*Game loop starts here*/
var gameLoop = function () {
    $(".container").on("click", function () {
        $(".player").stop().animate({
            bottom: "+=100px"
        }, 300, function () {
            $(".player").animate({
                bottom: "0"
            }, 800);
        });
    });
/* some more calls to updating player properties etc etc will come here*/
};
/*Game loop ends here*/

/*Run the Game Loop*/
setInterval(gameLoop, 16);

<小时/> 陈述我的问题:
如何防止游戏进行过程中出现延迟?

最佳答案

延迟是因为您每 16 毫秒分配一个新的点击处理程序。

在 gameLoop 函数之外提取以下代码:

$(".container").on("click", function () {
    $(".player").stop().animate({
        bottom: "+=100px"
    }, 300, function () {
        $(".player").animate({
            bottom: "0"
        }, 800);
    });
});

您还没有发布其余的代码,但请确保在 gameLoop 中仅更新游戏的状态,而不是重新创建保持游戏运行的机制。

关于javascript - 随着游戏的进行,游戏循环出现滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047154/

相关文章:

database - 强规范化关系数据库效率不高?

java开关性能优化

javascript - lodash-es 中的意外 token 'export'

javascript - 仅显示 1 个 Facebook 好友 - 使用 FB Javascript SDK jQuery

javascript - vue.js方法有什么区别

javascript - 使用 jQuery 从元素获取动态 css top 值

sql - Oracle SQL 中的高效四向联接

javascript - 如何使用 Google 跟踪代码管理器和 Backbone 路由器来跟踪页面浏览量?

jquery - 在 unslider 幻灯片放映中禁用向后动画

javascript - 根据屏幕宽度将 &lt;script src ="">&lt;/script&gt; append 到头部