用键盘按键打破JS中的无限循环

问题描述 投票:0回答:1

我正在尝试使用JavaScript制作游戏。我目前正在研究重力。我需要做一个无限循环。但是,我知道,如果不使用break语句,浏览器将崩溃。有什么方法可以实现仅在指定时才会发生的break语句?

这是我当前的循环:

for (i = 0; i < Infinity; i++) {
  if (moveY > 300) {
    moveY = moveY - i * 2 + 3;
    move(moveX, moveY);
  } else {
    i = 0;
  }
}
javascript html css infinite-loop game-development
1个回答
0
投票

您不会在JavaScript中进行游戏循环的无限循环。相反,您使用requestAnimationFrame

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>

events
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.