我正在尝试实现一个函数来改变变量的值(在一个简单的乒乓球游戏中是划桨速度),但是计时器运行得非常快,而且划桨速度似乎没有正确地改变。
我创建了一个函数,该函数在每次按下start game按钮时执行,我将其用作计时器:
function setTimer () {
setInterval(function () {
trialWindow += 1;
}, 1000);
console.log(trialWindow);
}按下start按钮即可执行此计时器
startBtn.addEventListener('click', setTimer);我还设置了另一个函数,用于在trialWindow变量是15的倍数时递增canvas.paddleOneVelocityY
function userSpeed () {
if (trialWindow % 15 === 0)
{canvas.paddleOneVelocityY = getRandomNumber(5, 20)};
console.log(canvas.paddleOneVelocityY);
}在startGame函数中调用以下函数:
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
gameInterval = window.setInterval(function() {
moveEverything();
drawEverything();
setTimer();
userSpeed();
}, 1000/fps);
}我尝试按照gameInterval中调用的函数的顺序将setTimer和userSpeed移动到不同的位置,但计时器似乎完全停止了。
任何帮助都将不胜感激!
发布于 2020-07-22 19:11:04
setTimer在每次调用时都会创建一个新的间隔计时器(一个重复的计时器)。您是从另一个间隔计时器的回调中调用它的:
gameInterval = window.setInterval(function() { // <== This function repeats
moveEverything();
drawEverything();
setTimer(); // <== This creates a repeating
userSpeed(); // timer every time it's called
}, 1000/fps);相反,只要调用setTimer一次,当您想要启动计时器时,它就会启动。
考虑到您的外部计时器以1000/fps毫秒运行,您可能需要查看requestAnimationFrame。
发布于 2020-07-22 19:16:51
这是你想要的:
function setTimer() {
setInterval(function () {
trialWindow += 1;
userSpeed();
console.log(trialWindow);
}, 1000);
}
function userSpeed() {
if (trialWindow % 15 === 0) {
canvas.paddleOneVelocityY = getRandomNumber(5, 20)
};
console.log(canvas.paddleOneVelocityY);
}
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
setTimer();
gameInterval = window.setInterval(function () {
moveEverything();
drawEverything();
}, 1000 / fps);
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="startGame()">Start</button>
</body>
</html>
https://stackoverflow.com/questions/63032785
复制相似问题