I want to write a little game where I can move a ball on a JavaFX Panel using the W, A, S, D keys.
I have a getPosX()
and setPosX()
but I don't know how to write a KeyListener
which will e.g. calculate setPosX(getPosX()+1)
if I press D.
What do I have to do?
From a JavaRanch Forum post.
Key press and release handlers are added on the scene and update movement state variables recorded in the application. An animation timer hooks into the JavaFX pulse mechanism (which by default will be capped to fire an event 60 times a second) - so that is a kind of game "loop". In the timer the movement state variables are checked and their delta actions applied to the character position - which in effect moves the character around the screen in response to key presses.