how to make my player move in diagonal lines and horizontal lines

时光怂恿深爱的人放手 提交于 2019-12-11 04:17:36

问题


i have the following code to make an ellipse move to the left right top and bottom. but now the player can only move in one direction at the time. so if the player moves to the left he cant move to the to the top or bottom. how do i make my code so the player can move both left and right and to the top and the bottom at the same time? any suggestions are appreciated. :)

see the code that i have so far:

void userInput() {
    if (keyPressed && (key == 's')) {
      speedY = 1;
      println("yes");
    }
    if (keyPressed && (key == 'w')) {
      speedY = -1;
      println("yes");
    }
    if (keyPressed && (key == 'd')) {
      println("yes");
      speedX = 1;
    }
    if (keyPressed && (key == 'a')) {
      println("yes");
      speedX = -1;
    }  
    if (keyPressed &&(key != 'a' && key != 'd')) {
      println("no");
      speedX = 0;
    }

    if (keyPressed &&(key != 'w' && key != 's')) {
      println("no");
      speedY =0;
    }
  }

void movement() {
    x = x + speedX;
    y = y + speedY;

}

回答1:


One way to do this is to use boolean values to keep track of which keys are pressed. Set them to true in keyPressed(), set them to false in keyReleased(), and use them to move your actor in the draw() function.

boolean upPressed = false;
boolean downPressed = false;
boolean leftPressed = false;
boolean rightPressed = false;

float circleX = 50;
float circleY = 50;

void draw() {
  background(200);  

  if (upPressed) {
    circleY--;
  }

  if (downPressed) {
    circleY++;
  }

  if (leftPressed) {
    circleX--;
  }

  if (rightPressed) {
    circleX++;
  }

  ellipse(circleX, circleY, 20, 20);
}

void keyPressed() {
  if (keyCode == UP) {
    upPressed = true;
  }
  else if (keyCode == DOWN) {
    downPressed = true;
  }
  else if (keyCode == LEFT) {
    leftPressed = true;
  }
  else if (keyCode == RIGHT) {
    rightPressed = true;
  }
}

void keyReleased() {
  if (keyCode == UP) {
    upPressed = false;
  }
  else if (keyCode == DOWN) {
    downPressed = false;
  }
  else if (keyCode == LEFT) {
    leftPressed = false;
  }
  else if (keyCode == RIGHT) {
    rightPressed = false;
  }
}


(source: happycoding.io)

More info can be found in this tutorial on user input in Processing.



来源:https://stackoverflow.com/questions/38804901/how-to-make-my-player-move-in-diagonal-lines-and-horizontal-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!