弹跳球出现故障

问题描述 投票:0回答:1

我在使用类创建弹跳球时遇到了问题。球移动了,但它卡在了页面的底部。请帮忙!! 谢谢!!!

球移动了,但它卡在了页面底部。

class particle{
  constructor(x,y,r){
    this.x=x;
    this.y=y;
    this.r=r;
  }
  
  bounce(xSpeed, ySpeed){
    this.xSpeed = xSpeed;
    this.ySpeed = ySpeed;
    
    if (this.x < 0 || this.x > width) {
        this.xSpeed *= -1;
    
    if (this.y < 0 || this.y > height) {
        this.ySpeed *= -1;
    }

    this.x += this.xSpeed;
    this.y += this.ySpeed;

  }
  
  display(){
    fill(0,255,0);
    stroke(0);
    strokeWeight(1);
    circle(this.x,this.y,this.r);
  }
}

let balloon;
function setup(){
  createCanvas(windowWidth,windowHeight);
  balloon = new particle(100, 100, 100);
  
}

function draw(){
  background(245);
  
  balloon.bounce(5,5);
  balloon.display();
 
  }
class p5.js
1个回答
0
投票

这是因为您将初始的

xSpeed
ySpeed
作为
bounce()
函数的输入参数。我对其进行了更改,以便
xSpeed
ySpeed
现在仅启动一次,然后根据球的位置进行更改,就像您预期的那样。

class particle
{
  constructor(x,y,r,xSpeed,ySpeed)
  {
    this.x=x;
    this.y=y;
    this.r=r;
    this.xSpeed = xSpeed;
    this.ySpeed = ySpeed;
  }
  
  bounce()
  {
    if (this.x < 0 || this.x > width)
    {
        this.xSpeed *= -1;
    }
    
    if (this.y < 0 || this.y > height)
    {
        this.ySpeed *= -1;
    }

    this.x += this.xSpeed;
    this.y += this.ySpeed;
  }
  
  display()
  {
    fill(0,255,0);
    stroke(0);
    strokeWeight(1);
    circle(this.x,this.y,this.r);
  }
}

let balloon;
  
function setup()
{
  createCanvas(windowWidth,windowHeight);
  balloon = new particle(100, 100, 100, 5, 5);
}

function draw()
{
  background(245);
  
  balloon.bounce();
  balloon.display();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.