在基本的p5js游戏中添加碰撞和得分



我对P5js很陌生,我正在努力检测头像(代码中名为"鸟"(和障碍物(椭圆(

我对此感到非常困难,我尝试在头像击中障碍物或椭圆时增加或扣除分数。

我已经尝试了各种方法,但代码仍然总是搞砸。所以我在征求意见。任何帮助将不胜感激。这是我现在的代码:

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();
}
}

Stack Overflow并不是真正为一般的"我该怎么做"类型的问题而设计的。它适用于特定的"我尝试了 X,预期为 Y,但得到了 Z"类型的问题。如果您指向行为与预期不同的特定代码行,那么您的运气会好得多。但我会尝试在一般意义上提供帮助。

你能做的最好的事情就是把你的问题分解成更小的步骤,然后一次一个地执行这些步骤。从空白草图重新开始,并显示单个矩形和单个圆。然后添加一些基本的冲突检测代码,当形状重叠时,该代码会将消息打印到控制台。您可能希望想象一个围绕圆圈的边界框,并使用矩形-矩形碰撞检测。然后添加第二个圆圈。然后让它与一系列圆圈一起工作。然后添加您的图像。

你不应该试图一次完成所有事情,或者在最终草图中实现所有逻辑。您应该隔离每个步骤,一次只处理一小块。然后,如果您遇到困难,您可以发布MCVE以及更具体的技术问题。祝你好运。

最新更新