I want to create a game where you control your character with the arrow keys. When I tried it you it first moved the character into the direction, stopped for a moment and only then began to continously move the character until I stopped. Now I want to know if I can somehow bypass that moment where no actions take place.
Also, I have the problem where I try to use multiple keys. It works when I press both keys at the same time, but when I first press one and then the other key, It doesn't work.
I use Java awt and JFrames.
The code:
public class Main extends JPanel implements MouseListener, ActionListener, ComponentListener, Runnable, KeyListener
{
private JFrame frame;
private Timer timer = new Timer(20, this);
private boolean draw = true;
int pX = 0;
int pY = 0;
public static void main(String[] args)
{
EventQueue.invokeLater(new Main());
}
@Override
public void run()
{
frame = new JFrame("Test");
frame.setMinimumSize(new Dimension(1000, 750));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(this);
frame.addKeyListener(this);
frame.setFocusable(true);
frame.pack();
frame.setVisible(true);
timer.start();
}
protected void paintComponent(Graphics g)
{
if(draw)
{
//Draw the character
draw = false;
}
}
@Override
public void actionPerformed(ActionEvent e)
{
this.repaint();
draw = true;
}
@Override
public synchronized void keyTyped(KeyEvent e)
{
switch(e.getExtendedKeyCode())
{
case KeyboardCodes.DOWN:
pY += 5;
break;
case KeyboardCodes.UP:
pY -= 5;
break;
case KeyboardCodes.LEFT:
pX -= 5;
break;
case KeyboardCodes.RIGHT:
pX += 5;
}
}
@Override
public synchronized void keyPressed(KeyEvent e)
{
switch(e.getExtendedKeyCode())
{
case KeyboardCodes.DOWN:
pY += 5;
break;
case KeyboardCodes.UP:
pY -= 5;
break;
case KeyboardCodes.LEFT:
pX -= 5;
break;
case KeyboardCodes.RIGHT:
pX += 5;
}
}
@Override
public void keyReleased(KeyEvent e)
{
}
}