对象运动的歧义

时间:2018-11-22 23:16:08

标签: java ambiguity

我正在尝试使用WASD在屏幕上移动一个矩形。我的问题是,当用户尝试以太快的速度两次更改操纵杆的方向时(假设您先向左按下,然后再次向右和向左再次超快),对象会冻结一秒钟,然后继续沿其方向移动。我愿意就如何解决它提出想法。谢谢。

全局变量

int velocityX = 0;
int velocityY = 0;
Boolean flagA = false;
Boolean flagD = false;
Boolean flagW = false;
Boolean flagS = false;
Sprite player = new Sprite(100, 100, 60, 60, "player", Color.BLACK);
Thread t1;
Thread t2;
Thread t3;

运动的线程定义(seOnKeyPressed)

t1 = new Thread(new Runnable() {
              @Override
              public void run() {
                  while(true) {
                      scene.setOnKeyPressed(e -> {
                            switch(e.getCode()) {
                            case A:
                                flagA = true;
                                player.velocityX = -1;
                                break;
                            case D:
                                flagD = true;
                                player.velocityX = 1;
                                break;
                            case W:
                                flagW = true;
                                player.velocityY = -1;
                                break;
                            case S:
                                flagS = true;
                                player.velocityY = 1;
                                break;
                            }
                });
                  }
              }
           });

线程定义(setOnKeyReleased)

t2 = new Thread(new Runnable() {
              @Override
              public void run() {
                  while(true) {
                      scene.setOnKeyReleased(e -> {
                            switch(e.getCode()) {
                            case A:
                                flagA = false;
                                player.velocityX = 0;
                                break;
                            case D:
                                flagD = false;
                                player.velocityX = 0;
                                break;
                            case W:
                                flagW = false;
                                player.velocityY = 0;
                                break;
                            case S:
                                flagS = false;
                                player.velocityY = 0;
                                break;
                            }
                });
                  }

              }
           });

AnimationTimer,用于更新对象在屏幕上的位置

AnimationTimer timer = new AnimationTimer() {

        @Override
        public void handle(long now) {
            player.setTranslateX(player.getTranslateX() + player.velocityX);
            player.setTranslateY(player.getTranslateY() + player.velocityY);
        }

    };

启动程序

//Starting threads
   t1.start();
   t2.start();

//AnimationTimer for updating X & Y location
   timer.start();

0 个答案:

没有答案