steering by the keys

Hi Freaks,

I’m trying to build a little shoot-game just for fun. But I have problems to handle the keyEvents well.

My SpaceShip should fly to the direction as long as the key (for example: VK_UP && VK_RIGHT --> fly to north-east) is been pressed. by this way a lot of events are thrown and I don’t know the right way to catch them (performantly).

Could you please post an example? To see, what I mean, please visit my applet:

http://www.gm.fh-koeln.de/~wi784/to/java/flight/flightJar.htm

The steering doesn’t work valid - that’s my problem.

greetings & thanks

Tobias

Hi,
The pattern I have seen used in games for capturing these sort of events is to just listen for the keypressed and keyreleased events and just set a boolean var to indicate which directional keys have been pressed. In your movement loop, you don’t wait for events, rather you just check the direction variables and process accordingly. If a key is held down, I think keytyped events are fired, but you don’t want to handle those, you just want to handle keypressed and keyrelseased events.

-Chris

Like this:


import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Game extends KeyAdapter
{
      private boolean up;
      private boolean down;
      private boolean left;
      private boolean right;

      private void mainLoop()
      {
            while (true)
            {
                  // check status of up, down, left, right
            }
      }

      public void keyPressed(KeyEvent e)
      {
            int code = e.getKeyCode();
            if (code = KeyEvent.VK_UP)
            {
                  up = true;
            }
            else if (code. = KeyEvent.VK_DOWN)
            {
                  down = true;
            }
            else if (code = KeyEvent.VK_LEFT)
            {
                  left = true;
            }
            else if (code = KeyEvent.VK_RIGHT)
            {
                  right = true;
            }
      }

      public void keyReleased(KeyEvent e)
      {
            int code = e.getKeyCode();
            if (code = (KeyEvent.VK_UP))
            {
                  up = false;
            }
            else if (code = KeyEvent.VK_DOWN)
            {
                  down = false;
            }
            else if (code = KeyEvent.VK_LEFT)
            {
                  left = false;
            }
            else if (code = KeyEvent.VK_RIGHT)
            {
                  right = false;
            }
      }
}

Doh!.. except the if (code = KeyEvent.VK_XX) should be if (code == KeyEvent.VK_UP).