通过keyListener获取多键

时间:2011-06-29 08:34:40

标签: java keylistener

我想用2个玩家来编程游戏。其中一个玩(w,a,s,d)其他玩家再见(y,g,h,j)。 但是如果其中一个玩家保持按键,键盘记录器就不能听其他一个键。我应该怎么做才能听到他们两个都可以听?


    @Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == 39)
        player1.setBounds((dim_player1.width += 5), dim_player1.height, 80, 120);
    else if (e.getKeyCode() == 37)
        player1.setBounds((dim_player1.width -= 5), dim_player1.height, 80, 120);
    else if (e.getKeyCode() == 40)
        player1.setBounds(dim_player1.width, (dim_player1.height += 5), 80, 120);
    else if (e.getKeyCode() == 38)
        player1.setBounds(dim_player1.width, (dim_player1.height -= 5), 80, 120);

}

这是我的简单代码,我想当玩家同时按38 + 39时,例如它同时执行这两项操作,但我无法理解我应该怎么做。

1 个答案:

答案 0 :(得分:0)

呃。在我的TZ上午6点,所以我可能错了,但是 - 线程化。将键盘状态存储在线程安全的设置/映射中,在按下事件时更新set / map,使用每个游戏勾号的状态来执行结果。

或者只使用bool数组。在大多数情况下也会起作用。例如:

static public enum camera_action {
  ESCAPE, // e.g. exit to main menu, terminate mouse capture etc
  MV_FORWARD, MV_BACKWARD, MV_STRAFE_LEFT, MV_STRAFE_RIGHT, MV_JUMP, MV_CROUCH, // etc
}

final protected SC_HashMap<Integer, camera_action> keymap = new SC_HashMap.linked<>();
protected boolean[] action_state = new boolean[camera_action.values().length];

final protected void set_default_keymap() {
  keymap.put( KeyEvent.VK_SHIFT, camera_action.MV_JUMP );
  keymap.put( KeyEvent.VK_CONTROL, camera_action.MV_CROUCH );
  keymap.put( KeyEvent.VK_W, camera_action.MV_FORWARD );
  keymap.put( KeyEvent.VK_S, camera_action.MV_BACKWARD );
  keymap.put( KeyEvent.VK_A, camera_action.MV_STRAFE_LEFT );
  keymap.put( KeyEvent.VK_D, camera_action.MV_STRAFE_RIGHT );
  keymap.put( KeyEvent.VK_ESCAPE, camera_action.ESCAPE );
}

protected void set_action_state( camera_action a, boolean new_state ) {
  action_state[a.ordinal()] = new_state;
}

protected boolean get_action_state( camera_action a ) {
  return action_state[a.ordinal()];
}

public void reset_action_state() {
  action_state = new boolean[camera_action.values().length];
}

@Override
public void keyPressed( KeyEvent e ) {
  camera_action a = keymap.get( e.getKeyCode() );
  if ( a != null )
    set_action_state( a, true );
}

@Override
public void keyReleased( KeyEvent e ) {
  camera_action a = keymap.get( e.getKeyCode() );
  if ( a != null )
    set_action_state( a, false );
}

我知道Oracle对Enum.ordinal()的政策 - 我对此并不了解。如果EnumSet可以使用它,那么我也可以使用ordinal()的契约。

而且 - 是的可能是Swing's KeyListener and multiple keys pressed at the same time。{/ p>