【发布时间】:2019-05-10 09:17:27
【问题描述】:
我想做什么:
我正在尝试使用 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);
}
}
错误:
未捕获的类型错误:this.generatePipes 不是函数
【问题讨论】:
-
你有一个带有匿名箭头函数的函数表达式,而不是函数声明。所以它没有被吊到顶部。调用函数时,全局变量
generatePipes仍然为空。因此,要么将generatePipes移动到原型并使用游戏实例,要么在调用它之前定义 generatePipes。
标签: javascript function canvas ecmascript-6