功能无法识别

时间:2019-05-10 09:17:28

标签: javascript function canvas

我要做什么:

我正在尝试使用p5.js库对Flappy Bird进行编码。


问题:该功能无法识别我定义的功能。


function Game() {

  this.pipes = generatePipes();
  setInterval(this.gameLoop, 1000 / 60);

  generatePipes = () => {
    const firstPipe = new Pipe(null, space);
    const secondPipeHeight = winHeight - firstPipe.height - space;
    const secondPipe = new Pipe(secondPipeHeight, space);
    return [firstPipe, secondPipe]
  }
  gameLoop = () => {
    this.update();
    this.draw();
  }
  update = () => {
    if (frameCount % 30 == 0) {
      this.pipes = this.generatePipes();
      this.pipes.push(...pipes);
    }
    this.pipes.forEach(pipe => pipe.x = pipe.x - 1);

  }

  draw = () => {
    this.pipes.forEach(pipe => pipe.draw());
  }
}
class Pipe {
  constructor(height, space) {
    this.x = 100;
    this.y = height ? winHeight - height : 0; // borunun y eksenine göre konumunu belirler
    this.width = pipeWidth;
    this.height = height || minPipeHeight + Math.floor(Math.random() * (winHeight - space - minPipeHeight * 2));
  }
  draw() {
    fill(124);
    noStroke();
    rect(this.x, this.y, this.width, this.height);
  }
}

错误:

  

未捕获的TypeError:this.generatePipes不是函数

3 个答案:

答案 0 :(得分:2)

function Game() {

  generatePipes = () => {
    const firstPipe = new Pipe(null, space);
    const secondPipeHeight = winHeight - firstPipe.height - space;
    const secondPipe = new Pipe(secondPipeHeight, space);
    return [firstPipe, secondPipe]
  }

  gameLoop = () => {
    this.update();
    this.draw();
  }

  this.pipes = generatePipes();
  setInterval(this.gameLoop, 1000 / 60);

  update = () => {
    if (frameCount % 30 == 0) {
    this.pipes = this.generatePipes();
    this.pipes.push(...pipes);
  }
  this.pipes.forEach(pipe => pipe.x = pipe.x - 1);

  }

  draw = () => {
    this.pipes.forEach(pipe => pipe.draw());
  }
}

此更新的代码应该可以使用。 在您的代码中,您在函数表达式之前调用了generatePipes()时将无法正常工作。仅当解释器到达您首先定义函数表达式的那行代码时,函数表达式才会加载。

答案 1 :(得分:0)

编写方式:您为变量 generatePipes 分配了一个函数,这意味着您只能在实例化变量后才能访问它。

您有两个选择:在使用 generatePipes 变量之前对其进行实例化,或将其声明为子函数。

function Game() {

  generatePipes = () => {
    ...
    return x;
  }

  this.pipes = generatePipes();
}

OR

function Game() {

  this.pipes = generatePipes();

  function generatePipes() {
    ...
    return x;
  }
}

答案 2 :(得分:0)

只需将您的功能分配给this

this.generatePipes = () => {...}
this.gameLoop = () => {...}
this.update = () => {...}
this.draw = () => {...}