【问题标题】:make speed 5 when shift key is pressed按下shift键时速度为5
【发布时间】:2016-08-08 21:13:35
【问题描述】:

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

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

【问题讨论】:

  • 您的代码中的keyPressedSHIFT 是什么?在您看来,key == 'w' && key == SHIFT 怎么可能是真的?
  • this question 可以帮到你
  • 尝试在location.x = loca...之前移动if (key == SHIFT) { ... }
  • 不行还是不行...

标签: java processing game-physics


【解决方案1】:

这两个if 语句永远不会两者都为真:

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

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

事实上,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 中,了解处理中的用户输入。

【讨论】:

  • @FutureCake 我已经编辑了我的答案,包括一个小例子来说明我在说什么。
  • 我在你的例子中做了同样的事情,但我一直得到同样的错误......就像我原来的问题一样:(
  • @FutureCake 你得到了什么确切的错误?如果您遇到新问题,请在新问题中发布更新的minimal reproducible example
  • 我没有收到任何错误。当我按下 shift 键时,椭圆停止移动。但这并不重要,我要采用一种全新的方法:)
  • @FutureCake 这听起来像是一个逻辑问题。请在新问题中发布minimal reproducible example,我们可以从那里开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多