I\'m attempting to create a simple pong game in Java, but I don\'t know how to have both players using the keyboard at the same time. The game is incomplete and I\'m working on
It's better to use a thread for animations. When you keyPressed
we will tell the program that the key is down. On keyReleased
we will tell the program that the key is up. In the thread we will read this value and determine if we want to move or not. This will also be much smoother.
First, you need to implement Runnable
in some class. You could even do it in your main class there.
Add the public void run
method.
In it will be something like:
while(true)
{
if(player1.upkeyIsDown() && player1.downKeyIsUp())
{
//move Player1 Up
}
else if(player1.downKeyIsDown() && player1.upKeyIsUp())
{
//move Player1 Down
}
//do similar for player 2
try{
Thread.sleep(50);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
This is semi-pseudo code, you'll have to implement how you save the key being down. In your KeyListeners, you need to call something in the main class to change these values, and then this thread will deal with the rest.
This thread also needs to be started. In your main/constructor somewhere write new Thread(this).start();