KeyListener / KeyBinding不会一致地触发

时间:2017-04-29 05:06:09

标签: java swing keylistener key-bindings

我正在尝试制作一个简单的游戏,我需要我的宇宙飞船在其中心旋转(使用A和D键),并相对于它面向的方向(W和S键)移动。

我得到了运动和旋转的数学计算,但我对主要听众有疑问。

当我编译时,关键监听器在前几次按键时工作正常。但是,如果我按下A(按下时向左旋转)然后切换到D然后再次切换到A,它将停止工作。按键的任何其他组合也会导致这种情况。

基本上,如果我按键过多,最终会停止工作。如果我走得很慢,按下键后我会再次开始工作,我想要工作几次。但是,如果我一次按下一串键(按A,然后是D,然后快速连续按下W),那么它就会完全停止工作,并且所有按键都无法响应。

我认为这不是处理速度问题,因为程序不会崩溃或产生任何内存错误。

我已经阅读了类似的问题,并看到人们建议不使用KeyListeners,而是使用KeyBindings,但我尝试了两者并得到了完全相同的问题。

以下是我的程序的更新代码(尝试制作MCVE): 我在中间注释的部分是键绑定的代码。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.math.*;
import java.net.URL;

public class Game extends JPanel implements ActionListener{

private Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame();
private Ship ship = new Ship();
private Timer gameTimer, turnRight, turnLeft, moveForward, moveBackward;
private static final int IFW = JComponent.WHEN_IN_FOCUSED_WINDOW;

public Game(){
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Study Buddy Menu");
    frame.setSize(800,700);
    frame.setLocation(dim.width/2 - 400, dim.height/2 - 350);

    turnLeft = new Timer(20, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            ship.setAngle(ship.getAngle() + ship.getTurnSpeed()); 
        }
    });
    turnRight = new Timer(20, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            ship.setAngle(ship.getAngle() - ship.getTurnSpeed()); 
        }
    });
    moveForward = new Timer(20, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            ship.setX(ship.getX() +  (float)Math.cos(Math.toRadians(ship.getAngle())));
            ship.setY(ship.getY() -  (float)Math.sin(Math.toRadians(ship.getAngle())));
            System.out.println("UP");
        }
    });
    moveBackward = new Timer(20, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            ship.setX(ship.getX() -  (float)Math.cos(Math.toRadians(ship.getAngle())));
            ship.setY(ship.getY() +  (float)Math.sin(Math.toRadians(ship.getAngle())));
            System.out.println("DOWN");
        }
    });
    this.setFocusable(true);
    this.requestFocus();
    /*getInputMap(IFW).put(KeyStroke.getKeyStroke('d'), "right");
    getActionMap().put("right", new MoveAction("d"));
    getInputMap(IFW).put(KeyStroke.getKeyStroke('a'), "left");
    getActionMap().put("left", new MoveAction("a"));
    getInputMap(IFW).put(KeyStroke.getKeyStroke('w'), "up");
    getActionMap().put("up", new MoveAction("w"));
    getInputMap(IFW).put(KeyStroke.getKeyStroke('s'), "down");
    getActionMap().put("down", new MoveAction("s"));*/

    this.addKeyListener(new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            //TURN
            if(e.getKeyCode() == KeyEvent.VK_D){
                turnLeft.start();   
                turnRight.stop();
            }
            if(e.getKeyCode() == KeyEvent.VK_A){ 
                turnRight.start();
                turnLeft.stop();
                }
            //MOVE
            if(e.getKeyCode() == KeyEvent.VK_W){
                moveForward.start();
                moveBackward.stop();
            }
            if(e.getKeyCode() == KeyEvent.VK_S){
                moveBackward.start();
                moveForward.stop();
            }

        }
        public void keyReleased(KeyEvent e){
            turnRight.stop();
            turnLeft.stop();
            moveForward.stop();
            moveBackward.stop();
        }
    });
    frame.add(this);
    repaint();
    gameTimer = new Timer(20, this);
    gameTimer.start();
    frame.setVisible(true);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    ship.draw(g);
}
public void actionPerformed(ActionEvent e) {
    repaint();

}
private class MoveAction extends AbstractAction {
    String d = null;
    MoveAction(String direction) {
        d = direction;
    } 
    public void actionPerformed(ActionEvent e) {
        switch (d){
            case "d": turnLeft.start(); turnRight.stop();break;
            case "a": turnRight.start(); turnLeft.stop();break;
            case "w": moveForward.start(); moveBackward.stop();break;
            case "s": moveBackward.start(); moveForward.stop();break;
        }

    }

}
class main {

public void main(String[] args) {
    Game game = new Game();
}

}

class Ship {
private float x, y, radius, speed, angle, turnSpeed;
private Image icon;
public Ship(){
    x = 400;
    y = 350;
    speed = 1;
    radius = 20;
    angle = 90;
    turnSpeed = 5;
    try {
        icon = ImageIO.read(new URL("https://i.stack.imgur.com/L5DGx.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}


//GETTERS
public float getX(){
    return x;
}
public float getY(){
    return y;
}
public float getTurnSpeed(){
    return turnSpeed;
}
public float getAngle(){
    return angle;
}
public float getRadius(){
    return radius;
}
public float getSpeed(){
    return speed;
}
public Image getIcon(){
    return icon;
}
//SETTERS
public void setX(float X){
    x = X;
}
public void setTurnSpeed(float S){
    turnSpeed = S;
}
public void setY(float Y){
    y = Y;
}
public void setAngle(float A){
    angle = A;
}
public void setSpeed(float S){
    speed = S;
}
public void setRadius(float R){
    radius = R;
}
public void setIcon(Image image){
    icon = image;
}
//DRAW
public void draw(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform at = new AffineTransform();
    at.setToRotation(Math.toRadians(angle-90), x, y);
    //at.translate(x, y);
    g2d.setTransform(at);
    g2d.drawImage(icon,(int)(x - radius), (int)(y - radius),(int)(radius * 2),(int)(radius * 2), null);
    g2d.dispose();
}
}
}

1 个答案:

答案 0 :(得分:2)

我正准备去睡觉所以我不能太深入地看待你的代码,但是一个表现良好的运动方法是这样的:

  • 您的KeyListener /键绑定/设置了一些变量,例如isTurningLeftisTurningRightisMovingForwardsisMovingBackwards
  • 然后你只有一个计时器在每次迭代时检查控制状态,并同时根据所有迭代计算运动。

同时跟踪每个按钮非常重要,这样您就可以获得所有信息。例如,您可以执行以下操作:

double turnRate = 0;
if (isTurningLeft) {
    turnRate -= maxTurnRate;
}
if (isTurningRight) {
    turnRate += maxTurnRate;
}
rotationAngle += timeElapsed * turnRate;

这样,如果两个按钮同时被按住,则转弯率只有0.这样可以避免许多奇怪的行为,比如坚持和口吃。但是,要做到这一点,您需要在一个地方知道两个按钮的状态。

修改

我修改了你的程序作为例子:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.net.URL;

public class KeyListenerGame extends JPanel implements ActionListener{
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new KeyListenerGame();
            }
        });
    }

//    private static final int IFW = JComponent.WHEN_IN_FOCUSED_WINDOW;
//    private Dimension   dim     = Toolkit.getDefaultToolkit().getScreenSize();
    private JFrame frame;
    private Ship   ship;
    private Timer  gameTimer;//, turnRight, turnLeft, moveForward, moveBackward;
    private KeyBindingController controller;

    // This is just an example. I recommend using
    // the key bindings instead, even though they
    // are a little more complicated to set up.
    class KeyListenerController extends KeyAdapter {
        boolean isTurningLeft;
        boolean isTurningRight;
        boolean isMovingForward;
        boolean isMovingBackward;

        @Override
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_A:
                    isTurningLeft = true;
                    break;
                case KeyEvent.VK_D:
                    isTurningRight = true;
                    break;
                case KeyEvent.VK_W:
                    isMovingForward = true;
                    break;
                case KeyEvent.VK_S:
                    isMovingBackward = true;
                    break;
            }
        }
        @Override
        public void keyReleased(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_A:
                    isTurningLeft = false;
                    break;
                case KeyEvent.VK_D:
                    isTurningRight = false;
                    break;
                case KeyEvent.VK_W:
                    isMovingForward = false;
                    break;
                case KeyEvent.VK_S:
                    isMovingBackward = false;
                    break;
            }
        }
    }

    // This could be simplified a lot with Java 8 features.
    class KeyBindingController {
        boolean isTurningLeft;
        boolean isTurningRight;
        boolean isMovingForward;
        boolean isMovingBackward;

        JComponent component;

        KeyBindingController(JComponent component) {
            this.component = component;
            // Bind key pressed Actions.
            bind(KeyEvent.VK_A, true, new AbstractAction("turnLeft.pressed") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isTurningLeft = true;
                }
            });
            bind(KeyEvent.VK_D, true, new AbstractAction("turnRight.pressed") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isTurningRight = true;
                }
            });
            bind(KeyEvent.VK_W, true, new AbstractAction("moveForward.pressed") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isMovingForward = true;
                }
            });
            bind(KeyEvent.VK_S, true, new AbstractAction("moveBackward.pressed") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isMovingBackward = true;
                }
            });
            // Bind key released Actions.
            bind(KeyEvent.VK_A, false, new AbstractAction("turnLeft.released") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isTurningLeft = false;
                }
            });
            bind(KeyEvent.VK_D, false, new AbstractAction("turnRight.released") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isTurningRight = false;
                }
            });
            bind(KeyEvent.VK_W, false, new AbstractAction("moveForward.released") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isMovingForward = false;
                }
            });
            bind(KeyEvent.VK_S, false, new AbstractAction("moveBackward.released") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isMovingBackward = false;
                }
            });
        }

        void bind(int keyCode, boolean onKeyPress, Action action) {
            KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, 0, !onKeyPress);
            String   actionName = (String) action.getValue(Action.NAME);
            component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
                .put(keyStroke, actionName);
            component.getActionMap()
                .put(actionName, action);
        }
    }

    public KeyListenerGame(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Study Buddy Menu");

        frame.add(this);
        frame.pack();
        frame.setLocationRelativeTo(null);

        gameTimer  = new Timer(20, this);
        controller = new KeyBindingController(this);
        ship       = new Ship(getSize());

        gameTimer.start();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        double secsElapsed = gameTimer.getDelay() / 1000.0;

        double maxSpeed     = ship.getSpeed();
        double maxTurnSpeed = ship.getTurnSpeed();
        double theta = Math.toRadians( ship.getAngle() );
        double x     = ship.getX();
        double y     = ship.getY();

        double turnSpeed = 0;
        if (controller.isTurningLeft) {
            turnSpeed -= maxTurnSpeed;
        }
        if (controller.isTurningRight) {
            turnSpeed += maxTurnSpeed;
        }

        theta += secsElapsed * Math.toRadians(turnSpeed);

        double speed = 0;
        if (controller.isMovingForward) {
            speed += maxSpeed;
        }
        if (controller.isMovingBackward) {
            speed -= maxSpeed;
        }

        double velX = speed * Math.cos(theta);
        double velY = speed * Math.sin(theta);

        x += secsElapsed * velX;
        y += secsElapsed * velY;

        ship.setX( (float) x );
        ship.setY( (float) y);
        ship.setAngle( (float) Math.toDegrees(theta) );

        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // Computes a preferred size based on the
        // dimensions of the screen size.
        int prefWidth  = screenSize.width / 2;
        // Compute 4:3 aspect ratio.
        int prefHeight = prefWidth * 3 / 4;
        return new Dimension(prefWidth, prefHeight);
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        ship.draw(g);
    }

    class Ship {
        private float x, y, radius, speed, angle, turnSpeed;
        private Image icon;
        public Ship(Dimension gameSize) {
//            x = 400;
//            y = 350;
//            speed = 1;
//            radius = 20;
//            angle = 90;
//            turnSpeed = 5;

            x = gameSize.width  / 2;
            y = gameSize.height / 2;
            radius = 20;
            angle  = -90;
            // 1/4 of the game height per second
            speed  = gameSize.height / 4;
            // 180 degrees per second
            turnSpeed = 180;

            try {
                icon = ImageIO.read(new URL("http://i.stack.imgur.com/L5DGx.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //GETTERS
        public float getX(){
            return x;
        }
        public float getY(){
            return y;
        }
        public float getTurnSpeed(){
            return turnSpeed;
        }
        public float getAngle(){
            return angle;
        }
        public float getRadius(){
            return radius;
        }
        public float getSpeed(){
            return speed;
        }
        public Image getIcon(){
            return icon;
        }
        //SETTERS
        public void setX(float X){
            x = X;
        }
        public void setTurnSpeed(float S){
            turnSpeed = S;
        }
        public void setY(float Y){
            y = Y;
        }
        public void setAngle(float A){
            angle = A;
        }
        public void setSpeed(float S){
            speed = S;
        }
        public void setRadius(float R){
            radius = R;
        }
        public void setIcon(Image image){
            icon = image;
        }
        //DRAW
        public void draw(Graphics g){
            Graphics2D g2d = (Graphics2D) g.create();
            //
            // Draw the ship's movement vector.
            double theta = Math.toRadians(angle);
            double velX  = speed * Math.cos(theta);
            double velY  = speed * Math.sin(theta);
            g2d.setColor(java.awt.Color.blue);
            g2d.draw(new java.awt.geom.Line2D.Double(x, y, x + velX, y + velY));
            //
            g2d.rotate(theta, x, y);
            int imgX = (int) ( x - radius );
            int imgY = (int) ( y - radius );
            int imgW = (int) ( 2 * radius );
            int imgH = (int) ( 2 * radius );
            g2d.drawImage(icon, imgX, imgY, imgW, imgH, null);
            //
            g2d.dispose();
        }
    }
}

除了控件之外,我还改变了其他一些东西:

  • 始终通过调用SwingUtilities.invokeLater(...)开始Swing程序。这是因为Swing运行在与main运行的线程不同的线程上。 https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
  • 我没有直接设置JFrame的大小,而是覆盖getPreferredSize并根据屏幕尺寸计算初始尺寸,然后在pack()上调用JFrame。这比尝试静态设置像素大小要好得多。此外,JFrame的大小包括其插图(例如标题栏),所以如果你打电话,例如jFrame.setSize(800,600)显示游戏的内容窗格实际上比800x600略小。
  • 我添加了一条显示船舶运动矢量的线,只是想象一下正在发生什么。这种事情很适合调试。
  • ship.draw我创建g g.create()的副本,因为g是Swing个人使用的图形对象。对传入的Graphics处理或设置转换这样的事情不是一个好主意。
  • 我稍微修改了旋转码。由于AWT坐标中的y轴是倒置的,因此正角度实际上是顺时针旋转,负角度是逆时针旋转。

有一些方法可以使键绑定代码更好,但我只是以最明显的方式做到这一点,所以你可以清楚地看到我实际在做什么。您必须为按下和释放的事件设置绑定。但是你会注意到它有一个模式,所以你可以编写一个小类来执行泛型布尔逻辑,而不是像我那样复制和粘贴。

Java 8 lambdas也会很好,但是我的Java 8计算机坏了。使用Java 8,你最终会得到类似的东西:

bind(KeyEvent.VK_A, "moveLeft", b -> isMovingLeft = b);

void bind(int keyCode, String name, Consumer<Boolean> c) {
    Action pressAction = new AbstractAction(name + ".pressed") {
        @Override
        public void actionPerformed(ActionEvent e) {
            c.accept(true);
        }
    };
    Action releaseAction = new AbstractAction(name + ".released") {
        @Override
        public void actionPerformed(ActionEvent e) {
            c.accept(false);
        }
    };
    // Then bind it to the InputMap/ActionMap like I did
    // in the MCVE.
}