我正在使用JavaScript开发游戏,我试图使一个点移动,但是一旦移动了一个点,它就不会保持相同的值。我试图将setInerval设置为var,然后将其清除,但是没有用。
[请让我知道我在做错什么,如何解决?
<!DOCTYPE html>
<html lang="en">
<head>
<script>
let x = 0;
let isKey = 0;
function goingUp() {
x -= 1;
}
function goingDown() {
x += 1;
}
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowDown' && isKey !== -1) {
setInterval(goingDown, 50);
isKey -= 1
} else if (event.key === 'ArrowUp' && isKey !== 1) {
setInterval(goingUp, 50);
isKey += 1
}})
let lastFrameTimeMs = 0, // The last time the loop was run
maxFPS = 60; // The maximum FPS we want to allow
function startGame(timestamp) {
// Throttle the frame rate.
if (timestamp < lastFrameTimeMs + (500 / maxFPS)) {
requestAnimationFrame(startGame);
return;
}
lastFrameTimeMs = timestamp;
console.log(x)
requestAnimationFrame(startGame);
}
requestAnimationFrame(startGame);
</script>
</head>
</html>
您是否尝试过setTimeout
而不是setInterval
?