FutureCake - 1 year ago 124
Java Question

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

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;

}
``````

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download