Reputation: 37
I have problem with the bouncing ball, while creating it using class. The ball move but it stuck at the bottom of the page. Please help!! Thank you!!!
The ball move but it stuck at the bottom of the page.
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();
}
Upvotes: 0
Views: 51
Reputation: 395
It's because you put the initial xSpeed
and ySpeed
as input parameter of the bounce()
function. I changed it so that the xSpeed
and ySpeed
now are initiated only once and later it gets changed based on the ball position, just like you intended.
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>
Upvotes: 0