#bouncing ball | how to make it accelerating as it moves down like a gravity simulation.

3 messages · Page 1 of 1 (latest)

uneven mulch
#

Hi coding friends, I am a beginning coding learner on coding train. I am trying to simulate the gravity. But I find it confusing when I am trying to set when it is gonna bounces back. now it just keeps bouncing back at the same height like playing basketball.

float y = 0;
float speed=2;
float g=2;

void setup(){
size(640,360);
}

void draw(){
background(0);
noStroke();
fill(255);
circle(width/2,y,50);
y=y+speed;
speed=speed+g;

if (y>=height){
speed=speed*-1+g;
}

println(speed,y);
}

prisma solstice
#

I think you change your code as follow.
float y = 0;
float speed = 2;
float g = 2;
float bounceEfficiency = 0.9; // Adjust this value to change how much energy is lost on each bounce

void setup() {
size(640, 360);
}

void draw() {
background(0);
noStroke();
fill(255);
circle(width / 2, y, 50);

// Apply gravity
y += speed;
speed += g;

// Check if the object has hit the ground
if (y >= height) {
// Reverse the direction of the speed and reduce its magnitude based on bounce efficiency
speed *= -bounceEfficiency;

// Optionally, add a small constant to simulate air resistance slowing down the object
speed -= g * 0.1;

}

println(speed, y);
}

#

when the object hits the ground (y >= height), we reverse the direction of speed by multiplying it by -bounceEfficiency. The bounceEfficiency value controls how much energy is lost during the bounce. A value of 0.9 means that 10% of the kinetic energy is lost on each bounce, making the object slow down over time. You can adjust this value to see how it affects the simulation.

Additionally, I subtract a small fraction of g from speed every time it bounces. This simulates the effect of air resistance, which gradually slows down the object over time. This part is optional but adds another layer of realism to the simulation.