Im writing a simple game that basically has two people control sprites and fight. I have written this program with a key listener but this is only allowing me to control one sprite at any given time. I am open to using a different method of keyboard input beside KeyListener
although I'd prefer to stick with my KeyListener
. I've heard of KeyBindings
but I couldn't really figure out how to use them. One idea I had was multithreading but I'm not really comfortable with that concept. Here is my code: (Please leave an example of what my code should be. Also, the 2nd sprite is controlled with a separate class which is almost identical to this one but just uses different keys. )
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
public class KeyHandler implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
Display.up = Display.up + 7;
}
if (key == KeyEvent.VK_DOWN) {
Display.down = Display.down + 7;
}
if (key == KeyEvent.VK_RIGHT) {
Display.right = Display.right + 7;
}
if (key == KeyEvent.VK_LEFT) {
Display.left = Display.left + 7;
}
if (key == KeyEvent.VK_SPACE) {
Display.fireMissile();
Display.whichSpriteInt = 0;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}