Reputation: 13
So I am trying to code pong in processing and everything is working fine, and I can move the paddles up and down perfectly, however, when you try to move two paddles at the same time, they don't move / it doesn't let you (I am going to make this a 2 player game so that 2 people can play using the same keyboard but with different keys for the different paddles).
I believe this is an issue with using "key" or "keyPressed", because I think it can't detect both or something? but I can't seem to figure out how to fix this or any alternatives. (Keep in mind that I know how to move the paddles, its just that you can't move them both at the same time with the different provided keys like im trying to)
I have two objects so far, "Player1" and "Player2"
keep in mind "y" is the y position which will either go up or down depending on the key pressed, and "speed" is just the speed that the paddle will move.
This is in Player1. Up = w, Down = s
void movement() {
if(keyPressed) {
if(key == 'w' || key == 'W') {
y = y - speed; //goes up
} else if (key == 's' || key == 'S') {
y = y + speed; //goes down
}
}
}
This is in Player2. Up = up arrow key, Down = down arrow key
void movement() {
if (keyPressed) {
if(key == CODED) {
if(keyCode == UP) {
y = y - speed; //goes up
} else if (keyCode == DOWN) {
y = y + speed; //goes down
}
}
}
}
No error messages, just doesn't let you move 2 paddles at the same time, which is something I'd like to do.
Upvotes: 1
Views: 705
Reputation: 210890
You've to use the keyPressed
and keyReleased()
events. The events are executed once when a key is pressed or released.
Set a state when a key is pressed, respectively reset the state when the key is released:
Boolean player1_up = false;
Boolean player1_down = false;
Boolean player2_up = false;
Boolean player2_down = false;
void keyPressed() {
if (keyCode == UP)
player1_up = true;
else if (keyCode == DOWN)
player1_up = true;
if (key == 'w' || key == 'W')
player2_up = true;
else if (key == 's' || key == 'S')
player2_down = true;
}
void keyReleasd() {
if (keyCode == UP)
player1_up = false;
else if (keyCode == DOWN)
player1_up = false;
if (key == 'w' || key == 'W')
player2_up = false;
else if (key == 's' || key == 'S')
player2_down = false;
}
Use the states player1_up
, player1_down
, player2_up
and player2_down
in the movement
functions.
Upvotes: 4