[java] Pong -- Keyboard events

Started by
2 comments, last by Jakkyl 21 years, 4 months ago
Hi, I''m making a Pong clone and right now, in 2 player mode, only one person can move their paddle at a given time. How can I make it so both paddles can move at the same time?
  
my keyPressed code... (KeyEvent e)

if (e.getKeyCode() == e.VK_W) {
        if (lPaddleY > 0) {
		lPaddleY -= 10;
		render();
	}
} else if (e.getKeyCode() == e.VK_S) {
	if ((lPaddleY + pPaddleHeight) < height) {
		lPaddleY += 10;
		render();
	}
}
if (players == 2) {
	if (e.getKeyCode() == e.VK_UP) {
		if (rPaddleY > 0) {
			rPaddleY -= 10;
			render();
         	}
        } else if (e.getKeyCode() == e.VK_DOWN) {
		if ((rPaddleY + pPaddleHeight) < height) {
			rPaddleY += 10;
			render();
		}
	}
}

  
I see why it doesn''t work, but I don''t know how to get it TO work...
Advertisement
Do it this way:

Create an array of booleans, one for each key on the keyboard. On a keydown event, set the boolean to true for that key and on a keyup event, set it to false.

Then, in your paddle movement logic, check the booleans to see if a key is being pressed. This allows you to have multiple keys pressed at the same time...
One possible answer is to do with the keyPressed.

When player1 presses a key only that key is detected, so when it comes to moving the paddles 'W' has been registered as being pressed, but player2 keys haven't.
You've got an event for single keystrokes, but what code is returned when two keys (i.e player1 and 2) are pressed at the same time.

Just a guess.

[Edit]

fizban got in first.

[edited by - RavNaz on December 6, 2002 5:36:00 PM]
SWEET! Thanks a lot. That made the movement of the paddles much smoother too. They were kinda jerky and slow, now they''re like butta''! Thanks again, I appreciate the help.

**Joshua

This topic is closed to new replies.

Advertisement