我正在尝试在 HTML5 Canvas 上构建一个小游戏,但在尝试在游戏中设置 1 分钟倒计时时遇到了一些麻烦。
以下代码包含timeKeeper
函数和animate
循环。
计时员
function timeKeeper(width, font, posX, posY, text) {
this.width = width;
this.x = posX;
this.y = posY;
this.font = font;
this.text = text;
this.numSeconds = 0;
this.time = 0;
this.draw = () => {
c.font = this.width + " " + this.font;
c.fillStyle = "white";
c.fillText(this.text, this.x, this.y);
}
this.update = () => {
setInterval(() => {
this.text -= 1;
},1000)
this.draw();
}
}
动画
// Animation Loop
function animate() {
requestAnimationFrame(animate)
c.clearRect(0, 0, canvas.width, canvas.height)
timeBoard.update()
//Move enemies
enemies.forEach((enemy) => {
//update score and time
scoreBoard.draw();
//draw labels
scoreLabel.draw();
timeLabel.draw();
//update enemies
enemy.update();
enemy.checkBoundary();
if (enemy.isTrue == true) {
enemies.splice(enemies.indexOf(enemy), 1);
// console.log(enemies);
}
if (enemies.length == 0) {
setTimeout(initEnemies(), 200)
}
//collision detection by checking color
if (enemy.color == "#2185C5") {
if (getDistance(enemy.x, enemy.y, ship[0].x, ship[0].y) < enemy.radius + ship[0].radius) {
enemy.color = "#FF00FF"
scoreBoard.update();
}
}
});
//create one particle
ship[0].update();
}
我认为这里发生的是 timeBoard.update()
函数在每一帧都被调用,导致倒计时非常快。
谁能帮我解决这个问题?
提前致谢。
最佳答案
setInterval
函数堆栈,这意味着它将继续创建 setInterval
实例。通过反复调用 timeBoard.update(),您将创建许多 setInterval 实例,从而使您的计时器运行得比应有的快。您可以将 update
方法更改为类似 init
的方法,然后在动画循环之外调用一次。
关于javascript - 在 HTML5 游戏中实现计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377873/