0

我是 javascript 新手,我尝试开发一个新游戏,我收到了这条消息,但我不明白为什么。我很高兴得到您的帮助!(错误发生在“this.top = (Math.random() * cvs.height) / 3 + 20;”行)。

const obstablesArray = [];

class Obstable {
  constructor(cvs) {
    this.top = (Math.random() * cvs.height) / 3 + 20;
    this.bottom = (Math.random() * cvs.height) / 3 + 20;
    this.x = cvs.width;
    this.width = 20;
    this.color = "red";
    this.cvs = cvs;
  }

  draw(ctx) {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, 0, this.width, this.top);
    ctx.fillRect(
      this.x,
      this.cvs.height - this.bottom,
      this.width,
      this.bottom
    );
  }

  update(gameSpeed) {
    this.x -= gameSpeed;
    this.draw();
  }
}

export function handleObstacle(bird, ctx, frame) {
  if (frame % 50) obstablesArray.unshift(new Obstable());

  for (let i = 0; i < obstablesArray.length; i++) {
    obstablesArray[i].update(this.ctx);
  }
  if (obstablesArray.length > 20)
    for (let i = 0; i < 20; i++) {
      obstablesArray.pop(obstablesArray[0]);
    }
}

我在这个类上创建了 cvs 并发送它:

import Bird from "/src/bird";
import { handleObstacle } from "./obstacles";

const cvs = document.getElementById("canvas1");
const ctx = cvs.getContext("2d");
cvs.width = 600;
cvs.height = 400;

let frame = 0;
let spacePress = false;
let angle = 0;
const bird = new Bird();

function animate() {
  ctx.clearRect(0, 0, cvs.width, cvs.height);

  bird.update(cvs, spacePress, angle);
  bird.draw(ctx);
  //handleParticiles(bird, ctx);
  handleObstacle(bird, ctx, frame);
4

1 回答 1

0

这是因为你没有cvs在这里传递给你的类构造函数:

export function handleObstacle(bird, ctx, frame) {
  if (frame % 50) obstablesArray.unshift(new Obstable()); //<-- here

  ...
}

cvs 当然是未定义的。

于 2021-01-10T21:20:06.413 回答