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
Don't use a KeyListener. You should be using Key Bindings
.
See Motion Using the Keyboard for more information.
I added the following code to the KeyboardAnimation
example from the above link, which will allow you to do what you want:
JLabel label2 = new JLabel( new ColorIcon(Color.GREEN, 40, 40) );
label2.setSize( label2.getPreferredSize() );
label2.setLocation(500, 500);
contentPane.add( label2 );
KeyboardAnimation animation2 = new KeyboardAnimation(label2, 24);
animation2.addAction("A", -3, 0);
animation2.addAction("D", 3, 0);
animation2.addAction("W", 0, -3);
animation2.addAction("S", 0, 3);
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();