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?
-
When I want to move the brick using an arrow key it doesn't work. two of three question here about paintComponent is about animation, to click to tag paintComponent, then to delete this question, – mKorbel Feb 21 '15 at 13:53
-
If it's a typical breakout game, then you don't move the *bricks* with arrow keys, you move the *paddle* with the arrow keys. – RealSkeptic Feb 21 '15 at 13:53
-
@RealSkeptic Yes I meant the paddle. (bad english) – Anass Amraoui Feb 21 '15 at 14:29
-
Well, if you are sure the articles you read are about moving the paddle rather than the bricks, how about adding links to a few of those articles so we can see what you are talking about? – RealSkeptic Feb 21 '15 at 14:31
2 Answers
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.

- 3,967
- 9
- 50
- 92
Theoretically there are two approaches:
- Loop asking an input, loop drawing the animation
- On a timer do an animation step and cause a repaint, and install input handlers
The second approach is what is used in the current operating systems, as it is not blocking, not polling, events do not tie different system aspects together. DOS did it otherwise.
So programs follow the more indirect event driven approach.

- 107,315
- 7
- 83
- 138