SFML community forums

Help => General => Topic started by: MarbleXeno on January 10, 2021, 09:24:50 pm

Title: Bouncing ball simulation
Post by: MarbleXeno on January 10, 2021, 09:24:50 pm
Hello. I want to create a ball simulation. Since im not very good with math i created something, that is not working. Video: https://youtu.be/aqPDNt7cuv0
As you can see the ball 'explodes' with high velocity. I can't prevent it.

CODE:
(click to show/hide)

It never stops. I think, that's because the modificator but i just can't implement it right.
Title: Re: Bouncing ball simulation
Post by: Laurent on January 11, 2021, 08:05:47 am
The classical equation for realistic gravity is, if I remember correctly:

initial_position = 0; // where the ball is at the beginning of the jump
initial_velocity = xxx; // some positive initial velocity
gravity = 9.81; // on earth

void update()
{
    time = clock.getElapsedTime().asSeconds();
    velocity = -0.5 * gravity * time * time + initial_velocity;
    position = velocity * time + initial_position;

    // handle bouncing
    if (position <= 0)
    {
        clock.restart();
        initial_velocity = -velocity; // * factor
        initial_position = position;
    }
}
(probably needs some adjustments, but that's the idea)

That's for Y axis. For X axis it's easier, velocity remains constant as there's no horizontal gravity.

To make the ball bounce, you have to invert velocity when it reaches the ground, and optionally multiply it with a factor because it loses energy when it touches the ground (factor < 1).
Title: Re: Bouncing ball simulation
Post by: MarbleXeno on January 11, 2021, 01:24:00 pm
So i made something that works (?) But i can't implement factor right. SO the animation loops, never stops.

CODE:
(click to show/hide)

When i do something with factor the ball sometimes stops, sometimes falls.
Title: Re: Bouncing ball simulation
Post by: Laurent on January 11, 2021, 02:21:39 pm
That's quite different from what I posted. It's a good thing to try to make your own version, but if you don't know what you're doing, don't do it ;)

Start with something similar to what I posted, make it work, and then tweak it if you need to.
Title: Re: Bouncing ball simulation
Post by: MarbleXeno on January 11, 2021, 02:53:38 pm
Okay, i'll try but for now, i did what i wanted, so thanks for the help.
Title: Re: Bouncing ball simulation
Post by: taliebram on February 02, 2021, 05:52:15 pm
https://www.youtube.com/watch?v=eED4bSkYCB8&t=805s


This is a very interesting video, which goes a bit further than you were considering, but it starts very simple, so if you only watch the first half you should get a better understanding about the physics/interaction.