Reputation: 301
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();
}
Upvotes: 0
Views: 1149
Reputation: 301
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;
}
}
Upvotes: 0
Reputation: 32627
Accelerate only if the ball does not lie on the ground:
if(ballPos.y < 590)
velocity += accelaration;
Btw, you should not set the ball position to 590 if you detect a collision. Instead, turn back the time to the moment when the ball hit the ground, invert the velocity and fast forward the amount of time you stepped back.
if ( ballPos.y >= 590 )
{
auto time = (ballPos.y - 590) / velocity;
//turn back the time
ballPos.y = 590;
//ball hits the ground
velocity *= -1;
//fast forward the time
ballPos.y += velocity * time;
}
Upvotes: 0