I’m making a 2-player Ping pong game. I tried moving 1 player at a time, it worked fine but when I held down the move buttons of both at once, one moved flawlessly but the other moved just a bit then it got stuck.
final int playerW = 15;
final int playerH = 200;
Player p1 = new Player(0, 100, playerW, playerH);
Player p2 = new Player(600 - playerW, 100, playerW, playerH);
void setup() {
size(600, 400);
}
void draw() {
background(50);
p1.display();
p2.display();
p1.move1();
p2.move2();
}
class Player {
int xPos, yPos, pW, pH;
int pV = 10;
Player(int x, int y, int w, int h) {
this.xPos = x;
this.yPos = y;
this.pW = w;
this.pH = h;
}
void display() {
fill(240);
rect(this.xPos, this.yPos, this.pW, this.pH);
}
void move1() { //<-----------------------player1's move function
if (keyPressed == true) {
if (key == 'w') {
this.yPos -= pV;
}
if (key == 's') {
this.yPos += pV;
}
}
}
void move2() { //<-----------------------player2's move function
if (keyPressed == true) {
if (keyCode == UP) {
this.yPos -= pV;
}
if (keyCode == DOWN) {
this.yPos += pV;
}
}
}
}
The way I fixed this (when I also made a pong game lol) I had an ArrayList that added a key when ever its held down and then removes it whenever you let go of it,
along the lines of this:
void keyTyped() {
if (!keysIn.contains(key)) {
keysIn.add(key);
}
}
void keyReleased() {
if (keysIn.contains(key)) {
keysIn.remove(new Character(key));
}
}
KeysIn being the ArrayList<Character>
you can then check for a letter in that arraylist and continue with your program
This code uses four boolean values to hold whether any of the array keys are pressed. In the keyPressed() function, the corresponding variable is set to true, and in the keyReleased() function, the corresponding variable is set to false. Then the draw() function uses those variable to move the circle depending on which arrow keys are currently pressed.
Shameless self-promotion: here is a tutorial on this approach.
You could also do something like use an array to store the keys being pressed, but honestly I like to use specific variables because it make the code easier to understand.
But in the end you should take whichever approach makes the most sense to you.