我正在制作经典的“在屏幕上四处移动图像”程序。我正在尝试使用键盘绑定代替键侦听器,但是到目前为止没有成功。
我的对象在链表中
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);
}
}
我不确定如何“激活”键绑定。应该在主循环中吗?是否应该在player.tick方法中调用该方法来更新播放器图像并随后绘制它?
另外,inputmap和actionmap如何与玩家对象关联?我尝试做类似的事情,但是没有用:
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类不兼容)。谁能指导我正确的方向?如果我不小心遗漏了一些重要信息,请告诉我(我确信我确实做到了)
您不需要“激活”键绑定,一旦填充,它就已经被激活ActionMap
。什么你做需要做的是落实的actionPerfomed方法Action
的对象。该Action
对象本质上是一个动作处理程序。一旦创建,它就不应执行任何操作,而应仅在实际执行操作后才执行操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句