With Acceleration


Use the arrow keys to move the player left and right.

The player now gradually accelerates from zero to top speed while a key is pressed.
Did you notice the side-effect caused by the way the movement is coded? If you hold RIGHT, release it, then hold LEFT, the player moves right, stops, then moves left. But if you hold RIGHT then start holding LEFT, " + the player will gradually change direction to the left. The code to stop the player is never called because a key is being held down at all times. And the player moves left when both keys are held down because LEFT is tested first. You can fix this by stopping the player whenever the movement direction changes. But look at the next example for a better solution.