Search code examples
c++directxphysicsgame-physics

Bouncing ball issue


I am currently working on the 2D Bouncing ball physics that bounces the ball up and down. The physics behaviour works fine but at the end the velocity keep +3 then 0 non-stop even the ball has stopped bouncing. How should I modify the code to fix this issue?

Here is the video shows how it works. Note: Bandicam cannot record the velocity transition between -3 and 0. So, it just shows -3 when the ball stops bouncing.
https://www.youtube.com/watch?v=SEH5V6FBbYA&feature=youtu.be

Here is the generated report: https://www.dropbox.com/s/4dkt0sgmrgw8pqi/report.txt

    ballPos         = D3DXVECTOR2( 50, 100 );
    velocity        = 0;
    acceleration    = 3.0f;
    isBallUp        = false;

void GameClass::Update()
{
    // v = u + at
    velocity += acceleration;

    // update ball position
    ballPos.y += velocity;

    // If the ball touches the ground
    if ( ballPos.y >= 590 )
    {
        // Bounce the ball
        ballPos.y = 590;
        velocity *= -1;
    }

    // Graphics Rendering
    m_Graphics.BeginFrame();
    ComposeFrame();
    m_Graphics.EndFrame();
}

Solution

  • Put a isBounce flag to make the velocity to zero when the ball stops bouncing.

     void GameClass::Update()
    {
        if ( isBounce )
        {
            // v = u + at
            velocity += acceleration;
    
            // update ball position
            ballPos.y += velocity;
        }
        else
        {
            velocity = 0;
        }
    
        // If the ball touches the ground
        if ( ballPos.y >= 590 )
        {
            if ( isBounce )
            {
                // Bounce the ball
                ballPos.y = 590;
               velocity *= -1;
            }
    
    
            if ( velocity == 0 )
            {
                isBounce = false;
            }
    }