I don't understand why it's just sinking into the floor. I'm guessing it's because it glitches below the floor, and then the velocity goes negative for an infinite time. I just don't know how to fix it
var gravity = 9.8
var velocity = 5;
var circleOne;
function setup() {
createCanvas(400, 400);
circleOne = new newCircle(200, 50, 50, "black");
}
function draw() {
background("white");
circleOne.display();
circleOne.bounce();
}
class newCircle {
constructor(x,y,radius,color) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.velocity = 1;
}
display() {
fill(this.color)
ellipse(this.x,this.y,this.radius);
}
bounce() {
if (this.y + this.radius > height) {
this.velocity = -this.velocity * 0.5
}
else if (this.y < 0) {
this.velocity = -this.velocity * 0.5
}
else {
this.velocity += 1;
}
this.y += this.velocity
}
}
You have told the ball to flip the velocity every time it reaches below a certain point. But flipping the velocity does not necessarily mean that the ball will be above the threshold the next frame. So if the ball is below the threshold for two consecutive frames, it will flip twice, making the velocity exactly how it was two frames ago.
The ball will sink because the velocity keeps flipping every frame once it's too low.
You should set an extra boolean to true when you flip the velocity, then make sure to not flip it again as long as this boolean is true. You can set the boolean back to false once the ball has gone far enough up above the threshold.
However, if your goal is to make a somewhat more sophisticated physics engine, I highly recommend you to read this article. It has helped me a ton in the past while working on my own physics engine.