Hey, I decided that because when I set out to make a game 5 days ago, and I couldn't because I didn't know how to control stuff with the keyboard, I needed to learn how to create a program that could do something like this, but I had no idea how. I searched on the internet for hours, and eventually gave up and resorted to mouse events, from copied and pasted code. Then, someone contacted me and asked me to send them the code I had used for KeyListeners, and I told them I hadn't because I didn't know how, and that kind person gave me this gem.
The first thing you need to do is in the class you want to move, you must implement KeyListener
In the class that you implemented KeyListener, you need the instance of the window or canvas that you're using and you need to dopublic class Example implements KeyListener{ /* Other game stuff (updates, constructors, other stuff) */ }
(instance of game window or canvas).addKeyListener(this);
Then you need to add 3 methods in the same class because they are abstract in KeyListener and need to be over written since you're implementing KeyListener
After that, all you need to do is make the game recognize the keys and give it actions for thempublic void keyPressed(KeyEvent e){ }//key being held down public void keyReleased(KeyEvent e){ }//key released public void keyTyped(KeyEvent e){ }//not exactly sure, I never use
In public void keyPressed(KeyEvent e) or whichever void you want to use that you just added (the code above), you need to add
Then you have to check the int against the possible codes for keys (java has them built in)public void keyPressed(KeyEvent e){ int key = e.getKeyCode(); }
so
would say Pressed Space whenever you hit spacepublic void keyPressed(KeyEvent e){ int key = e.getKeyCode(): if(key == KeyEvent.VK_SPACE){ System.out.println("Pressed Space"); } }
if your using eclipse, you can get all the keycodes when you type if(key == KeyEvent.), it'll bring up the keycodes
After that I was fine, and I was able to make my game functional!
Hooray for that!