有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java(libGDX)按键输入单元测试:使用robot模拟按键

我想使用一个机器人来模拟用户按下左箭头键,然后对下面libGDX的“isKeyPressed”方法使用这个模拟,但我一直得到以下错误:无法调用“com.badlogic.gdx.Input.isKeyPressed(int)”,因为“com.badlogic.gdx.gdx.Input”为空。如何初始化它,使其不为空

类游戏屏幕测试{

@Test
void movementLeft() throws AWTException {
    int x = 10;

    Robot robot = new Robot();
    int keyCodeLeft = KeyEvent.VK_LEFT;
    robot.keyPress(keyCodeLeft);
    robot.keyRelease(keyCodeLeft);

    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        x -= 5;
    }

    assertEquals(5, x);
}

}


共 (1) 个答案

  1. # 1 楼答案

    Gdx.input只是Gdx类上的一个public static字段。您可以将其初始化为实现Input接口的任何东西

    这意味着您可以创建自己的类,该类实现Input,并且知道Robot,以便它可以查询机器人的按键状态,例如:

    public class RobotInput implements Input {
    
        private Robot robot;
    
        public RobotInput(Robot robot) {
            this.robot = robot;
        }
    
        /* loads of other methods from the Input interface omitted for brevity */
    
        @Override
        public boolean isKeyPressed(int key) {
            return robot.isKeyPressed(key);
        }
    }
    

    然后你可以初始化Gdx.input,比如:

    Robot robot = new Robot();
    Gdx.input = new RobotInput(robot);
    
    robot.keyPress(Input.Keys.LEFT);
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        x -= 5;
    }
    
    assertEquals(5, x);