I am making a simple game(my first time using key reader) and am using WASD inputs to move the character. I want to make it so that if you press, say, W and A at the same time, you go diagonal. Does anyone know how to do this?
Asked
Active
Viewed 1,149 times
1
-
ok awesome. so where are you stuck so far? any code or pseudocode? – Caffeinated Dec 10 '13 at 23:25
-
Please take a look at http://stackoverflow.com/a/2624161/257501. It is exactly what you need. – Saša Šijak Dec 10 '13 at 23:26
-
2Basically, you can't. A `KeyEvent` is raised for a single key only. Instead what you need to do is monitor for the `keyPressed` and `keyReleased` events and change the state of certain flags you create internally to you application - for [example](http://stackoverflow.com/questions/15897947/problems-with-javas-paint-method-ridiculous-refresh-velocity/15900205#15900205) and [example](http://stackoverflow.com/questions/20202477/moving-player-in-semi-cardinal-directions-using-java-canvas/20202804#20202804) – MadProgrammer Dec 10 '13 at 23:26
-
You can extend the KeyListener and KeyEvent classes under the java.awt.event package, or use the Scanner class for more string-oriented input. – Coder101101010 Dec 10 '13 at 23:28
1 Answers
1
Don't use a KeyListener. Swing was designed to be used with Key Bindings
.
Either way you can't listen for multiple keys at once so you need to keep track of which keys have been pressed. Since you want to do animation you would generally use a Swing Timer to schedule the animation. Then every time the Timer fires you check which keys are pressed and move you character based on the keys pressed.
Check out KeyboardAnimation.java
source code from Motion Using The Keyboard for an example that demonstrates this approach. This article also gives reasons why key bindings are preferred over a KeyListener.

camickr
- 321,443
- 19
- 166
- 288