Java-Gaming.org
Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
Featured games (78)
games approved by the League of Dukes
Games in Showcase (404)
games submitted by our members
Games in WIP (289)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How to listen multiple Key presses?  (Read 490 times)
0 Members and 1 Guest are viewing this topic.
Offline Andre Lopes

Junior Member





« Posted 2013-03-18 03:42:56 »

Hello Forum!
Im having issues!

In my game, the player controls a snake, but i cant make it move right and up at the same time, or down and left, etc;;;

It can only go one direction at a time...
I researched a lot, but couldnt make it work.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
 @Override
    public void keyPressed(KeyEvent e) {
       
        boolean setaPraCima = false;
        boolean setaPraBaixo = false;
        boolean setaPraDireita = false;
        boolean setaPraEsquerda = false;
       
        //System.out.println("Pressed : Key Code :: " + e.getKeyCode() + " == " + e.getKeyChar());
       if (e.getKeyCode() == 38) { // Seta pra cima
           setaPraCima = true;
            gameUpdate.moveSnakeUp();
        } else
            if (e.getKeyCode() == 40)
            {
                setaPraBaixo = true;
                gameUpdate.moveSnakeDown();
            }else
                if(e.getKeyCode() == 39)
                {
                    setaPraDireita = true;
                    gameUpdate.moveSnakeRight();
                } else
                    if(e.getKeyCode() == 37)
                    {
                        setaPraEsquerda = true;
                        gameUpdate.moveSnakeLeft();
             
                    }
       
        gameUpdate.GameUpdate();

    }
Offline ReBirth
« Reply #1 - Posted 2013-03-18 07:18:07 »

Remove the ELSE.

Offline davidc

Senior Member


Medals: 4
Projects: 2



« Reply #2 - Posted 2013-03-18 11:25:38 »

I would change the way you're responding to key events by not implementing any game logic within the event listeners. Your program really shouldn't be driven by these event methods, as you will only receive one event a time. You also don't want to be updating the game entities every time an event is received - this leaves the program at the mercy of how rapidly the player can hammer the keyboard.

An alternative is to do only one simple thing during key event handlers, and that's register the fact that a key has been pressed (or released). The idea is that you have a boolean variable for each key that you're interested in. Or an array of booleans if you want to capture lots of different keystrokes. You then listen for keyDown and keyUp events. When a keyDown is received, set the variable to true. When a keyUp is received, set the variable for that key to false.

Your main program loop then only has to check the state of these variables to see what is being pressed and act accordingly. Your game loop (which runs in its own thread) might do something along these lines:

1  
2  
3  
4  
5  
while (not finished)
  1. figure out what the player wants to do by looking at these key variables
  2. calculate what the game entities want to do, by applying AI logic
  3. update the scene, checking for collisions etc
  4. render everything


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Andre Lopes

Junior Member





« Reply #3 - Posted 2013-03-18 13:47:17 »

Thanks for the answers m8's;

I just made the game update in the control because i waas learning how to make it render in screen.
This time, im making the thread to do the gameloop.

Also,I took of the else too for a test, and it still happened.

I tried something like this :

"An alternative is to do only one simple thing during key event handlers, and that's register the fact that a key has been pressed (or released). The idea is that you have a boolean variable for each key that you're interested in. Or an array of booleans if you want to capture lots of different keystrokes. You then listen for keyDown and keyUp events. When a keyDown is received, set the variable to true. When a keyUp is received, set the variable for that key to false."

But it didnt work.. I made a list and worked on it, and was a mess!!!
Do you have any implementation example ,please?

Ty guys!!
Offline davidc

Senior Member


Medals: 4
Projects: 2



« Reply #4 - Posted 2013-03-18 14:10:43 »

This is a very basic keyboard handler class that you can use to listen for multiple key presses. It will respond to the first 128 key codes as defined in the KeyEvent class. If you need to respond to codes above this range, just increase the array size accordingly. You can see all of the codes here:
http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.awt.event.KeyEvent.CHAR_UNDEFINED

And now for Keyboard.java:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Keyboard {

    private static boolean[] pressed = new boolean[128];

    public static boolean isPressed(int key) {
        return pressed[key];
    }
 
   public static KeyListener listener = new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            int code = e.getKeyCode();
            if (code < pressed.length) {
                pressed[code] = true;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            int code = e.getKeyCode();
            if (code < pressed.length) {
                pressed[code] = false;
            }
        }
    };
}


The class defines a static member which is the listener, and can be added to your JPanel (or Applet) as follows:
1  
panel.addKeyListener(KeyBoard.listener);


Checking if a key has been pressed in your thread is as easy as:
1  
2  
3  
4  
5  
6  
if (Keyboard.isKeyPressed(KeyEvent.VK_LEFT)) {
    ...
}
if (Keyboard.isKeyPressed(KeyEvent.VK_DOWN)) {
    ...
}


One known limitation of this code is that if a key is pressed and released before your main game loop thread has a chance to read its state, then it will be missed. I have a solution to this, but have edited it out just to make the example a lot simpler to follow. It isn't such a big deal.[/code][/code]
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #5 - Posted 2013-03-18 17:45:34 »

Here's the listener that I use. I got it from Notch.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
public class Input implements KeyListener {

   public List<Key> keys = new ArrayList<Key>();
   
   public Key up = new Key();
   public Key down = new Key();
   public Key left = new Key();
   public Key right = new Key();
   public Key exit = new Key();
   
   public Input(Main game) {
      game.addKeyListener(this);
   }
   
   @Override
   public void keyPressed(KeyEvent e) {
      toggle(e, true);
   }

   @Override
   public void keyReleased(KeyEvent e) {
      toggle(e, false);
   }

   @Override
   public void keyTyped(KeyEvent e) { }
   
   private void toggle(KeyEvent e, boolean pressed) {
      if (e.getKeyCode() == KeyEvent.VK_UP) up.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_DOWN) down.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_LEFT) left.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_RIGHT) right.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_ESCAPE) exit.toggle(pressed);
   }
   
   public void releaseAll() {
      for (Key key : keys) key.down = false;
   }
   
   
   public class Key {
      public boolean down;
     
      public Key() {
         keys.add(this);
      }
     
      public void toggle(boolean pressed) {
         if (pressed != down) down = pressed;
      }
   }
}

Check out my website!
Offline Andre Lopes

Junior Member





« Reply #6 - Posted 2013-03-25 16:47:21 »

IT WORKED!
Like a charm!!!!

I love you xD
Pages: [1]
  ignore  |  Print  
 
 

Play Revenge of the Titans! The situation is critical. We need fancy commanders to defend Earth, the moon, Mars!
 
Browse for soundtracks for your game!

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

The invasion has landed! On Mars! And you're there to beat 'em!
cubemaster21 (42 views)
2013-05-17 21:29:12

alaslipknot (51 views)
2013-05-16 21:24:48

gouessej (79 views)
2013-05-16 00:53:38

gouessej (79 views)
2013-05-16 00:17:58

theagentd (87 views)
2013-05-15 15:01:13

theagentd (81 views)
2013-05-15 15:00:54

StreetDoggy (123 views)
2013-05-14 15:56:26

kutucuk (147 views)
2013-05-12 17:10:36

kutucuk (147 views)
2013-05-12 15:36:09

UnluckyDevil (157 views)
2013-05-12 05:09:57
Complex number cookbook
by Roquen
2013-04-24 12:47:31

2D Dynamic Lighting
by Oskuro
2013-04-17 16:46:12

2D Dynamic Lighting
by Oskuro
2013-04-17 16:45:57

2D Dynamic Lighting
by Oskuro
2013-04-17 16:23:20

Noise (bandpassed white)
by Roquen
2013-04-05 17:36:01

Noise (bandpassed white)
by Roquen
2013-04-03 16:17:38

Java Data structures
by Roquen
2013-03-29 13:21:12

Topic Request
by kutucuk
2013-03-22 21:42:01
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!
Page created in 0.18 seconds with 21 queries.