这是我在游戏循环方面的小尝试。 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/