我正在p5.js中跟踪编码火车的飞扬的小鸟挑战。一切顺利,直到我尝试运行该程序为止,“ Pipes总是在我第一次跳动时向上移动。这是我第一次敲空格键。我对这里发生的事情一无所知。管道的位置值永远不会与keyPressed函数相交,因此我很好奇管道向上移动的位置。
let bird;
let pipes = [];
let pipe;
function setup() {
createCanvas(400, 600);
bird = new Bird();
pipe = new Pipe();
pipes.push(new Pipe());
}
function draw() {
background(0);
bird.update();
bird.show();
pipe.prints();
for (let i = 0; i < pipes.length; i++) {
pipe.prints();
pipes[i].show();
pipes[i].update();
pipe.prints();
}
pipe.prints();
}
function keyPressed() {
if (key == ' ') {
bird.up();
}
function Bird() {
this.x = 64;
this.y = height / 2;
this.gravity = 0.9;
this.lift = -20;
this.velocity = 0;
this.show = function() {
fill(255);
ellipse(this.x, this.y, 32, 32);
}
this.up = function() {
this.velocity += this.lift;
}
this.update = function() {
this.velocity += this.gravity;
this.velocity *= 0.9;
this.y += this.velocity;
if (this.y > height) {
this.y = height;
this.velocity = 0;
}
if (this.y < 0) {
this.y = 0;
this.velocity = 0;
}
}
}
function Pipe() {
this.top = random(height / 2);
this.bottom = random(height / 2);
this.x = width;
this.w = 20;
this.speed = 3;
this.show = function() {
fill(255);
rect(this.x, 0, this.w, this.top);
rect(this.x, height - this.bottom, this.w, this.bottom);
}
this.update = function() {
this.x -= this.speed;
}
this.prints = function() {
print("Top: " + this.x + " Bottom: " + this.w);
}
}