繁体   English   中英

按下换档键时使速度为5

[英]make speed 5 when shift key is pressed

我有以下代码来使播放器移动:

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键时,我的播放器停止移动了...为什么会发生这种情况? 欢迎任何帮助我解决此问题的建议:)

这两个if语句永远不会都是真的:

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

在调用draw()函数期间, key变量将只有一个值。

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

而且,由于您要检测多个按键,因此您需要执行我在另一个问题中告诉您的操作:您需要使用一组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;
  }
}

有关更多信息, 请参见参考资料本教程中有关处理中用户输入的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM