javaanimationbreakout

Why do we need to use a Timer each time we want to keep moving graphics with arrow keys?


I want to build a brekaout game. When I want to move the piddle using an arrow key it doesn't work. So I read a few articles and I saw that they use a timer to do that. Can you give me the reason why they do that?


Solution

  • If you think about it, the answer is fairly straight forward. When you press and hold the arrow key you need to find out how far the paddle needs to move along its X axis.

    Without having a timer, there is no way to control the new offset over n elapsed seconds.

    Basic Physics formula D = S * T (Distance = Speed * Time)

    Whenever we press the key down, a timer could be started, we then find the new distance to be added/subtracted to the current position by multiplying a constant speed variable by the elapsed time.

    This shall also allow for fluid movement, instead of staggering the movement by a fixed distance on each keypress.