我有以下代码使椭圆移动到左上方和下方。但现在玩家只能在一个方向上移动。因此,如果玩家向左移动,他就无法移动到顶部或底部。我如何制作我的代码,以便玩家可以同时向左和向右移动到顶部和底部?任何建议表示赞赏。 :)
查看我到目前为止的代码:
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;
}
答案 0 :(得分:1)
执行此操作的一种方法是使用boolean
值来跟踪按下的键。将它们设置为true
中的keyPressed()
,将其设置为false
中的keyReleased()
,并使用它们在draw()
函数中移动您的演员。
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;
}
}
diagonal movement http://happycoding.io/tutorials/processing/images/input-14.gif
可以在this tutorial中找到有关处理中用户输入的更多信息。