我对P5js很陌生,我正在检测头像(在代码中命名为#39;鸟')和障碍物(椭圆)
我在这方面遇到了很多困难,我试图在头像遇到障碍物或椭圆时加上或扣除分数。
我尝试了各种方法,但代码总是搞砸了。所以我要求建议。任何帮助表示赞赏。这是我现在的代码:
let wW = window.innerWidth
let wH = window.innerHeight
let x = 0
let posX = wW/2
let posY = wH/2
let spdX //+0.5 -> -0.5
let spdY
let isBallMoving = true
let degree = 0
let myBalls = []
let maxBall = 20
let bro
function preload() {
bro = loadImage('images/bro.png');
}
function setup() {
createCanvas(wW, wH);
//set timer 1000ms=1sec
bird = new Bird();
angleMode(DEGREES)
ellipseMode(CENTER)
// ellipse(mouseX, mouseY, 50, 50)
for(let i = 1; i < maxBall; i++) {
let ball = {
posX: random(wH,wW),
posY: random(0,wH),
size: random(4,16),
spdX: random(-4, 4),
spdY: random(-1, 1),
hue: random(0, 360)
}
myBalls.push(ball)
}
}
function draw() {
background(120);
bird.update();
bird.show();
stroke(255)
strokeWeight(4)
ellipse(x, 200, 100, 100)
x = x + 3
if (x > wW) {
x = 0
}
degree += 0.5
for(let i = 0; i < myBalls.length; i++) {
//detect x
if (myBalls[i].posX >= wW || myBalls[i].posX <= 0) {
myBalls[i].spdX *= +1
}
//detect แกน y
if (myBalls[i].posY >= wH || myBalls[i].posY <= 0) {
myBalls[i].spdY *= +1
}
//animate
if (isBallMoving === true) {
myBalls[i].posX += myBalls[i].spdX
myBalls[i].posY += myBalls[i].spdY
}
myBalls[i].size = 40
noFill()
strokeWeight(3)
stroke(myBalls[i].hue, 80, 360)//120
//bubble
ellipse(myBalls[i].posX, myBalls[i].posY, myBalls[i].size,myBalls[i].size)
if (myBalls[i].posX > width) {
myBalls[i].posX = 0;
}
if (myBalls[i].posX < 0) {
myBalls[i].posX = wW - 3;
}
if (myBalls[i].posY < 0) {
myBalls[i].posY = wH - 3;
}
}
this.collidemyBalls = function(){
this.life -= 1
}
}
function Bird(_pos, _vel, _score, _life){
this.pos = _pos
this.vel = _vel
this.score = _score
this.life = _life
this.y = height/2;
this.x = width/2;
this.gravity = 0.7;
this.lift = -12;
this.velocity = 0;
this.show = function() {
imageMode(CENTER)
image(bro,this.x, this.y ,160, 70)
/* 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 keyPressed() {
if (key == ' ') {
bird.up();
}
}
答案 0 :(得分:0)
Stack Overflow并非真正针对一般&#34;我如何做到这一点&#34;输入问题。这是特定的&#34;我试过X,期望Y,但得到了Z而不是#34;输入问题。如果您指向一个与您的预期不同的特定代码行,您将获得更好的运气。但是我会在一般意义上尝试提供帮助。
您可以做的最好的事情是break your problem down into smaller steps并一次采取一个步骤。从空白草图重新开始,显示单个矩形和单个圆。然后添加一些基本的collision detection代码,在形状重叠时将消息输出到控制台。您可能想要想象一下围绕圆圈的边界框并使用矩形 - 矩形碰撞检测。然后添加第二个圆圈。然后让它与一系列圆圈一起工作。然后添加您的图片。
您不应该尝试一次完成所有事情,或者在最终草图中实施所有逻辑。你应该隔离每一步,一次只处理一小块。然后,如果您遇到问题,可以发布MCVE以及更具体的技术问题。祝你好运。