Lets say I have a method which controls some character movement like the following:
void Player::moveRight( Uint32 ticks )
{
if( speedx < maxspeed ) { speedx += accel; }
x += speedx * ( ticks / 1000.f );
//collision
if( x > (float)( 800 - width ) ) { x = (float)( 800 - width ); }
}
maxspeed = 300 and accel = 2 ( also, speedx starts at 0 )
Now there is nothing wrong with this, until I add in a constant deceleration / friction into the equation. Basically, I have a constant deceleration of 1 which is subtracted from the speed each frame. This is so if the character is not moving, they come to a gradual stop.
The problem is this: If speedx = 299 because of the deceleration, my if statement is still true, and it proceeds to add accel which brings up the speed to 301, past the maxspeed.
What would be some good solutions to this problem, which will allow me to have any acceleration and deceleration values and not trip up the if statement?
Change it to:
In this case, if acceleration causes the speed to go over the maximum it will simply set the speed to the maximum. Otherwise is will simply accelerate as normal.
Or, you could do: