【发布时间】:2018-06-04 04:50:49
【问题描述】:
我正在创建一个 2d 游戏,玩家可以在其中射击子弹。我试图弄清楚当玩家按键时如何调用 shoot 方法。我正在使用 Key Bindings,这对我来说是新的。我已经阅读了 API,但仍然无法正常工作。建议会有帮助
这是我的键盘输入代码:
public PlayerTwo (){
playertwo = Toolkit.getDefaultToolkit().createImage("cal.png");
bullets = new ArrayList();
tm.start();
InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up.pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up.released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down.pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down.released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left.pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "left.released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right.pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "right.released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), "space.pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true), "space.released");
am.put("up.pressed", new MoveAction(-1, 0));
am.put("up.released", new MoveAction(0, 0));
am.put("down.pressed", new MoveAction(1, 0));
am.put("down.released", new MoveAction(0, 0));
am.put("left.pressed", new MoveAction(0, -1));
am.put("left.released", new MoveAction(0, 0));
am.put("right.pressed", new MoveAction(0, 1));
am.put("right.released", new MoveAction(0, 0));
//Shoot.getActionMap();
}
【问题讨论】:
-
am.put("space.pressed", new ShootAction()); ShootAction 类来改变“拍摄”标志的状态,通过它你的“主循环”可以决定应该做什么 -
我可以重写我的子弹类来改变状态吗?
-
我会避免它,因为你正在耦合逻辑。最好让“射击动作”改变模型/控制器的状态,让它决定这实际上意味着什么
-
周围有很多例子,this is one 我最近做了这证明了解耦工作流的想法
标签: java swing graphics jframe key-bindings