我正在尝试使用JavaScript制作一个游戏。我目前正在制作引力。我需要的是做一个无限循环。但是,我知道如果我不使用break语句,浏览器就会崩溃。有没有什么方法可以实现一个只有当我指定时才会发生的break语句?
这是我当前的循环:
for (i = 0; i < Infinity; i++) {
if (moveY > 300) {
moveY = moveY - i * 2 + 3;
move(moveX, moveY);
} else {
i = 0;
}
}
您不会在JavaScript中为游戏循环创建无限循环。相反,您使用requestAnimationFrame
const p = document.querySelector('#p');
function gameloop(time) {
time *= 0.001; // convert to seconds
p.style.transform = `translate(${100 + Math.cos(time) * 100}px, ${100 + Math.sin(time) * 100}px)`;
requestAnimationFrame(gameloop);
}
requestAnimationFrame(gameloop);
html, body {
height: 100%;
margin: 0;
overflow: hidden;
}
.sprite {
position: absolute;
left: 0;
top: 0;
background: red;
color: white;
border-radius: 1em;
padding: 0.5em;
}
<div class="sprite" id="p">player</div>
如果你想要输入,你可以使用事件
const p = document.querySelector('#p');
let x = 100;
let y = 100;
let dir = 0.2;
const vel = 100; // 100 pixels per second
const turnSpeed = Math.PI; // half a turn per second
const keys = [];
let previousTime = 0;
function gameloop(currentTime) {
currentTime *= 0.001; // convert to seconds
deltaTime = currentTime - previousTime;
previousTime = currentTime;
if (keys[37]) dir -= turnSpeed * deltaTime;
if (keys[39]) dir += turnSpeed * deltaTime;
const dx = Math.cos(dir) * vel * deltaTime;
const dy = Math.sin(dir) * vel * deltaTime;
x = (x + dx + window.innerWidth) % window.innerWidth;
y = (y + dy + window.innerHeight) % window.innerHeight;
p.style.transform = `translate(${x}px, ${y}px) rotate(${dir}rad)`;
requestAnimationFrame(gameloop);
}
requestAnimationFrame(gameloop);
window.addEventListener('keydown', (e) => {
keys[e.keyCode] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.keyCode] = false;
});
html, body {
height: 100%;
margin: 0;
overflow: hidden;
}
.sprite {
position: absolute;
left: 0;
top: 0;
background: red;
color: white;
border-radius: 1em;
padding: 0.5em;
}
<div class="sprite" id="p">player</div>
<div>click here then press <- or -></div>