如何使我的玩家沿对角线和水平线移动 [英] how to make my player move in diagonal lines and horizontal lines

查看:75
本文介绍了如何使我的玩家沿对角线和水平线移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码使椭圆移动到左上角和右下角.但是现在玩家一次只能在一个方向上移动.因此,如果玩家向左移动,他将无法移至顶部或底部.我该如何编写代码,以便播放器可以同时向左和向右移动以及同时移动到顶部和底部?任何建议表示赞赏. :)

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;

}

推荐答案

一种方法是使用boolean值来跟踪按下了哪些键.在keyPressed()中将它们设置为true,在keyReleased()中将它们设置为false,然后使用它们在draw()函数中移动actor.

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;
  }
}


(来源: happycoding.io )


(source: happycoding.io)

有关处理方面的用户输入,请参见本教程.

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

这篇关于如何使我的玩家沿对角线和水平线移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆