随着游戏的进行,游戏循环滞后

时间:2014-02-26 16:20:58

标签: javascript jquery performance optimization game-loop

这是我与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);

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

1 个答案:

答案 0 :(得分:4)

延迟来自于您每16毫秒分配一个新的点击处理程序。

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

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

您尚未发布其余代码,但请确保在gameLoop中仅更新游戏状态,并且不会重新创建保持游戏运行的机制。