我按照 Youtube 上的 The Coding Train 教程创建了飞扬的小鸟游戏。(https://www.youtube.com/watch?v=cXgA1d_E-jY)
原始指令创建pipes
为ball
对象,但我将我的指令修改为创建为类。
我有两个问题。1)我在pipes
数组中创建的管道索引没有显示在屏幕上,2)ball.goup();
,这将由屏幕上的任何操作触发keyPressed()
,但console.log
显示它正在工作。我应该如何修改我的代码?谢谢。
let ball;
let pipes = [];
function setup() {
createCanvas(700, 600);
ball = new Ball();
pipes.push(new Pipe());
}
function draw() {
background(0);
ball.show();
ball.falldown();
if (frameCount % 60 == 0) {
pipes.push(new Pipe());
}
//since have splice, count from back to avoid uncounted indices
for (let i = pipes.length - 1; i >= 0; i--) {
pipes[i].show();
pipes[i].move();
if (pipes[i].hits(ball)) {
console.log("hit");
}
if (pipes[i].offscreen()) {
pipes.splice(i, 1);
}
}
}
function keyPressed() {
if (key == ' ') {
ball.goup;
console.log('up');
}
}
class Ball {
constructor(x = 50, y = height / 2, g = 0.6, v = 0, l = -20) {
this.x = x;
this.y = y;
this.gravity = g;
this.velocity = v;
this.lift = l;
}
goup() {
this.velocity += this.lift;
}
falldown() {
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;
}
}
show() {
noStroke();
fill(255);
ellipse(this.x, this.y, 25, 25);
}
}
class Pipe {
constructor(x =width, y=0, w=100, t=random(2/height), b=random(2/height), s=2, c=false) {
this.x = x;
this.y = y;
this.w = w;
this.top = t;
this.bottom = b;
this.speed = s;
this.colorchange = c;
}
hits(ball) {
if (ball.y < this.top || ball.y > height - this.bottom) {
if(ball.x > this.x && ball.x < this.x + this.w){
this.colorchange = true;
return true;
}
}
this.colorchange = false;
return false
}
move() {
this.x -= this.speed;
}
show() {
fill(255);
if (this.colorchange) {
fill(255, 0, 0);
}
rect(this.x, this.y, this.w, this.top);
rect(this.x, height - this.bottom, this.w, this.bottom);
}
//delete pipe indices from the array when pipes are off screen
offscreen() {
if (this.x < -this.w) {
return true;
} else {
return false;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>