我正在制作一个经典的“在屏幕上移动图像”程序。我试图让按键绑定(bind)工作,而不是使用按键监听器,但到目前为止还没有成功。
我的对象位于链接列表中
public LinkedList<GameObject> object = new LinkedList<GameObject>();
并通过添加到此列表
public void addObject(GameObject object){
this.object.add(object);
}
我的KeyBinding类如下
public class KeyBindings extends JPanel{
private static final String accelerate = "accelerate";
public KeyBindings(){
System.out.println("test");
registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "UP-press", new ShuttleMove(accelerate));
}
public void registerKeyBinding(KeyStroke keyStroke, String name, Action action) {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
class ShuttleMove extends AbstractAction {
public ShuttleMove(String movement) {
if (movement.equals("accelerate")){
//this.setVelocityForward(this.getVelocityForward() + 0.1);
System.out.println("accelerate");
}
}
public void actionPerformed(ActionEvent e) {
}
}
}
我的 Player 类,它扩展了 GameObject 类,看起来(稍微精简)为:
public class Player extends GameObject {
Handler handler;
public Player(int x, int y, ID id, int width, int height, int rotation,double totalRotation, Handler handler, double velocityForward, double velocityRotate){
super(x, y, id, width, height, rotation, totalRotation);
this.handler = handler;
}
public void tick(){
x += this.getVelocityForward();
y += this.getVelocityForward();
}
public void render(Graphics2D g2d){
try {
player = ImageIO.read(new File("src/Game/images/shuttle3.png"));
} catch (IOException e) {
e.printStackTrace();
}
AffineTransform old = g2d.getTransform();
AffineTransform at = AffineTransform.getTranslateInstance(x,y);
g2d.drawImage(player, at,null);
g2d.setTransform(old);
}
}
但我不确定如何“激活”键绑定(bind)。它应该在主循环中吗?它应该在player.tick方法中调用来更新玩家图像并随后绘制它吗?
此外,输入映射和 Action 映射如何与玩家对象关联?我尝试做这样的事情,但没有成功:
public void registerKeyBinding(KeyStroke keyStroke, String name, Action action) {
for (int i = 0; i < handler.object.size(); i++){
GameObject player = handler.object.get(i);
//find player
if (player.getID() == ID.Player){
InputMap im = player.getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = player.getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
}
}
我认为我的播放器应该如何转换为 JComponent,但我不确定这是如何完成的(因为 Eclipse 告诉我它与我的 GameObject 类不兼容)。谁能引导我朝正确的方向前进?如果我不小心遗漏了一些重要信息(我确信我遗漏了),请告诉我
最佳答案
您不需要“激活”键绑定(bind),一旦您填充ActionMap
,它就已经激活了。您要做需要做的是实现Action
对象的actionPerfomed方法。 Action
对象本质上是一个操作处理程序。一旦创建,它就不应该做任何事情,而应该只在实际执行操作后才做事情。
关于java - 在何处以及如何实例化输入映射和 Action 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657366/