我想创建一个游戏,您可以用箭头键控制角色。当您尝试该操作时,它首先将角色移向该方向,停了片刻,然后才开始连续移动角色,直到我停下来。现在,我想知道是否可以以某种方式绕过没有动作的那一刻。
另外,我在尝试使用多个键时遇到了问题。当我同时按下两个键时,它可以工作,但是当我先按一个键,然后再按另一个键时,它不起作用。
我使用Java awt和JFrames。
代码:
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)
{
}
}