微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript 游戏在一段时间后滞后

如何解决Javascript 游戏在一段时间后滞后

我正在尝试制作 2d 赛车游戏。启动时它工作顺利,但一段时间后它开始滞后。我在这个游戏中使用类和 requestAnimationFrame。 我不知道为什么 stackoverflow 说得更多,因为我已经完成了。我的问题是我不知道为什么它会滞后,我想是因为如果对象是在循环中创建的,我不知道。我是初学者。

这是代码

import { Car,RoadStrip,ObsCar } from "./engine.js";

// requestAnimationFrame support //

const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

window.requestAnimationFrame = requestAnimationFrame;

// VARIABLES //

const gameArea = document.querySelector(".gameArea");
const road = document.querySelector(".road");
const upBtn = document.querySelector(".n-up");
const downBtn = document.querySelector(".n-down");
const rightBtn = document.querySelector(".n-right");
const leftBtn = document.querySelector(".n-left");
const roadArea = road.getBoundingClientRect();
const score = document.querySelector(".score_counter");

// Player Car //

const playerCar = new Car();
playerCar.pushInDOM();
const car = playerCar.carElement;

// Lines on Road //

let lines = [];
let lineVeLocity = 7;

for (let i = 0; i <= 400; i += 80) {
  const line = new RoadStrip();
  line.create();
  line.top = (i) + (line.topDiff + i);
  line.lineNode.style.top = `${line.top}px`;
  lines.push(line);
}

// Obstacle Cars //

let obsCars = [];

for (let i = 0; i < 3; i++) {
  const obsCar = new ObsCar(roadArea.width);
  obsCar.y = ((i+1) * 300) * -1;
  obsCar.respawn(roadArea.height,roadArea.width);
  obsCars.push(obsCar);
}

// Controller Btns //

let directions = {
  ArrowUp: false,ArrowDown: false,ArrowRight: false,ArrowLeft: false
};

[upBtn,downBtn,leftBtn,rightBtn].forEach(btn => {
  btn.addEventListener("touchstart",startInteract);
  btn.addEventListener("touchend",endInteract);
});

// Functions //

function startInteract(e) {
  e.preventDefault();
  const clickedKey = e.target.dataset.dir;
  directions[clickedKey] = true;
  if (!playerCar.gameStart) {
    getThingsstart();
    obsCarHandler();
  }
  if (playerCar.gameStart === false) {
    playerCar.gameStart = true;
  }
  moveCar();
}

function endInteract(e) {
  e.preventDefault();
  const clickedKey = e.target.dataset.dir;
  directions[clickedKey] = false;
}

function stripHandler() {
  lines.forEach(line => {
    line.top += lineVeLocity;
    line.runStrips(line.lineNode);
    if (line.lineNode !== undefined && line.top > roadArea.height + 80) {
      line.restash(line.lineNode);
    }
  });
}

function obsCarHandler() {
  obsCars.forEach(car => {
    car.create();
    car.getIn(car.ObsCarElement);
    if (crash(playerCar.carElement,car.ObsCarElement)) {
      playerCar.gameStart = false;
    }
  });
}

function crash(car,obscar) {
  let carBound = car.getBoundingClientRect();
  let obsCarBound = obscar.getBoundingClientRect();
  
  return !((carBound.bottom < obsCarBound.top) || (carBound.top > obsCarBound.bottom) || (carBound.right < obsCarBound.left) || (carBound.left > obsCarBound.right));
}

function getThingsstart() {
  if (Number(score.textContent) > 100) {
    lineVeLocity = 8;
  } else if (Number(score.textContent) > 200) {
    lineVeLocity = 9;
  } else if (Number(score.textContent) > 300 && Number(score.textContent) < 400) {
    lineVeLocity = 10;
  } else {
    lineVeLocity = 12;
  }
  stripHandler();
  let needscore = Number(score.textContent);
  needscore += 0.1;
  score.textContent = needscore.toFixed(1);
  if (Number(score.textContent) >= 20 && Number(score.textContent) % 30 === 0) {
  }
  window.requestAnimationFrame(getThingsstart);
}

function moveCar() {
  let anim;
  if (directions.ArrowUp && playerCar.y < (roadArea.height - (car.height + 4))) {
    playerCar.y += playerCar.veLocity;
    playerCar.animate();
    let anim = window.requestAnimationFrame(moveCar);
  } if (directions.ArrowDown && playerCar.y > 0) {
    playerCar.y -= playerCar.veLocity;
    playerCar.animate();
    let anim = window.requestAnimationFrame(moveCar);
  } if (directions.ArrowLeft && playerCar.x > 0) {
    playerCar.x -= playerCar.veLocity;
    playerCar.animate();
    let anim = window.requestAnimationFrame(moveCar);
  } if (directions.ArrowRight && playerCar.x < (roadArea.width - (car.width + 5))) {
    playerCar.x += playerCar.veLocity;
    playerCar.animate();
    let anim = window.requestAnimationFrame(moveCar);
  }
}

和类的代码。(你不需要阅读这个,但如果你可以

class Car {
  constructor() {
    this.x = 8;
    this.y = 10;
    this.veLocity = 4;
    this.carModel = "Audi";
    this.carElement = null;
    this.gameStart = false;
  }
  pushInDOM() {
    const carNode = document.createElement("img");
    carNode.setAttribute("src",`./assets/vehicles/${this.carModel}.png`);
    carNode.setAttribute("alt","Car");
    carNode.setAttribute("class","car");
    carNode.style.left = "8px";
    carNode.style.bottom = "10px";
    document.querySelector(".road").appendChild(carNode);
    this.carElement = carNode;
  }
  animate() {
    
    if (this.carElement) {
      this.carElement.style.bottom = `${this.y}px`;
      this.carElement.style.left = `${this.x}px`;
    }
    window.requestAnimationFrame(() => {
      this.animate();
    });
  }
}

class RoadStrip {
  constructor() {
    this.top = 0;
    this.lineNode = undefined;
    this.topDiff = 25;
  }
  create() {
    const line = document.createElement("div");
    this.lineNode = line;
    line.classList.add("line");
    document.querySelector(".road").appendChild(line);
  }
  runStrips(lineNode) {
    lineNode.style.top = `${this.top}px`;
  }
  restash(lineNode) {
    this.top = -105;
    lineNode.style.top = `${this.top}px`;
  }
}

const obsCarModels = ["Black_viper","Mini_truck","Ambulance","Mini_van","Police","taxi","truck","Car"];

class ObsCar {
  constructor(width) {
    this.x = Math.trunc((Math.random() * Math.trunc(width - 48)) + 1);
    this.y = -100;
    this.model = obsCarModels[Math.trunc(Math.random() * obsCarModels.length)];
    this.ObsCarElement = null;
  }
  create() {
    const carNode = document.createElement("img");
    carNode.setAttribute("src",`./assets/vehicles/${this.model}.png`);
    carNode.setAttribute("alt","Obstacle Car");
    carNode.setAttribute("class","car");
    this.ObsCarElement = carNode;
    carNode.style.left = `${this.x}px`;
    carNode.style.zIndex = "3";
    carNode.style.top = `${this.y}px`;
    document.querySelector(".road").appendChild(carNode);
  }
  getIn(node) {
    this.y += 2;
    node.style.top = `${this.y}px`;
    window.requestAnimationFrame(() => {
      this.getIn(node);
    });
  }
  respawn(height,width) {
    if (this.y > Math.trunc(height)) {
      this.y = -100;
      this.x = Math.trunc((Math.random() * Math.trunc(width - 48)) + 1);
      this.ObsCarElement.style.left = `${this.x}px`;
      this.model = obsCarModels[Math.trunc(Math.random() * obsCarModels.length)];
      this.ObsCarElement.setAttribute("src",`./assets/vehicles/${this.model}.png`);
    }
    window.requestAnimationFrame(() => {
      this.respawn(height,width);
    });
  }
}
export { Car,ObsCar };

如果有人帮忙,那就太棒了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。