KeyListener - how to make program react to the key that was pressed twice?
So, shortly...
My mini game:
When I press a 'Space bar' key - the first ball (A) stops moving, and the second ball (B) starts moving.
The problem: How to make the second ball (B) stop moving with a same (Space bar) key?
What i need: 1st time 'Space bar' pressed - first ball stops. 2nd time 'Space bar' pressed - second ball stops.
How to do that?
I manage to make them both stop if i set that balls stop moving after different keys pressed. But I don't need that.
Code :
public void run() {
while(running){
if(BallA.ballMoves)
BallA.move();
if(!BallA.ballMoves){
BallB.move();
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
BallA.ballMoves = false;
}
Sorry, if I'm writing in a wrong sub-forum...
Re: KeyListener - how to make program react to the key that was pressed twice?
You need a way to keep track of the state of the key presses. Assign a different value to a variable for each state: No presses, one press, two presses, ????
How many states are there? Is there a 'three pressed' state or does the state restart at No presses?
1 Attachment(s)
Re: KeyListener - how to make program react to the key that was pressed twice?
Quote:
Originally Posted by
Norm
You need a way to keep track of the state of the key presses. Assign a different value to a variable for each state: No presses, one press, two presses, ????
How many states are there? Is there a 'three pressed' state or does the state restart at No presses?
no presses - first ball moves.
one press - first ball stops, second ball starts to move.
two presses - second ball stops (both are not moving).
Then some small action happens in the game and the thing with a 'space bar' key should restart.
I'm making a small basketball shooting game.
1st thing what I need is to set shot's accuracy. So there is a cross on which one ball is moving up and down, the other ball moves - left and right. I'm trying to stop them both with 'space bar' key.
Attachment 1568
When both balls will be stopped, shot's accuracy will be calculated and the shot will happen. After the first shot, I will need to set an accuracy for the second shot and so on and on.
I hope you understand what I'm trying to say.
Sorry for my bad english....
Re: KeyListener - how to make program react to the key that was pressed twice?
How are you thinking of keeping track of the state of the key presses? Can you post the logic the program needs to use to keep track of the key press state?
It will require a variable with values for each different state and some if statements to determine the current state and statements to change the state from the current state to the next state.