按下shift键时使速度为5

时间:2016-08-08 12:29:32

标签: java processing game-physics

我有以下代码让我的玩家移动:

class Player {

  PVector direction;
  PVector location;
  float rotation;
  int speed;


  Player() {
    location = new PVector(width/2, height/2);
    speed =2;
  }

  void visualPlayer() {
    direction = new PVector(mouseX, mouseY);
    rotation = atan2(direction.y - location.y, direction.x - location.x)/ PI * 180;
    if (keyPressed) {
      if ((key == 'w' && dist(location.x, location.y, direction.x, direction.y)>5) || (key == 'w' && key == SHIFT && dist(location.x, location.y, direction.x, direction.y)>5)) {
        speed = 2;
        location.x = location.x + cos(rotation/180*PI)*speed;
        location.y = location.y + sin(rotation/180*PI)*speed;

        if (key == SHIFT) {
          speed = 5;
        }
      }
    } else {
      location.x = location.x;
      location.y = location.y;
    }

    println(speed);
    ellipse(location.x, location.y, 10, 10);
  }
}

当我按下w键时,播放器朝着鼠标的方向移动。但是如果我按下shift键,我想让玩家移动得更快。但是现在当我按下shift键时我的播放器停止移动......为什么会发生这种情况?我欢迎任何帮助我解决这个问题的建议:)

1 个答案:

答案 0 :(得分:0)

这两个if语句绝不会两者为真:

if ((key == 'w' ) {
    if (key == SHIFT) {

key变量在调用draw()函数时只有一个值。

实际上,key变量的值永远不会为SHIFT。相反,您需要使用keyCode变量。

由于您尝试检测多个按键,因此您需要执行我在your other question中要求您执行的操作:您需要使用一组boolean值来跟踪哪些按下键,然后在draw()功能中使用它们。

这里有一个小例子,可以准确显示我在说什么:

boolean wPressed = false;
boolean shiftPressed = false;

void draw() {
  background(0);

  if (wPressed && shiftPressed) {
    background(255);
  }
}

void keyPressed(){
  if(key == 'w' || key == 'W'){
    wPressed = true;
  }
  if(keyCode == SHIFT){
    shiftPressed = true;
  }
}

void keyReleased(){
  if(key == 'w' || key == 'W'){
    wPressed = false;
  }
  if(keyCode == SHIFT){
    shiftPressed = false;
  }
}

有关详细信息,请参阅处理中的用户输入the referencethis tutorial

相关问题