0

the key input works however there is a delay when more than two keys are pressed at once. Also there is a 1 second delay when switching directions. I was wondering how I could fix this issue?

 public void keyPressed( KeyEvent ke ) 
 { 
   switch(ke.getKeyCode()) {
   case KeyEvent.VK_DOWN: spaceship.ypos+=12; break;
   case KeyEvent.VK_UP: spaceship.ypos-=12; break;
   case KeyEvent.VK_LEFT: spaceship.xpos-=12; break;
   case KeyEvent.VK_RIGHT: spaceship.xpos+=12; break;

   }
  repaint();

}

If more code is needed to understand what I am talking about, I can add more.\

Edit: I fixed my problem by adding a main class with a thread that constantly checks if the booleans are active so there was no delay.

    public class MainLoop implements Runnable{
    public MainLoop(){
    }
    public void run(){
        while(true){
            if(up){ spaceship.ypos-=8; }
            if(down){ spaceship.ypos+=8; }
            if(left){ spaceship.xpos-=8; }
            if(right){ spaceship.xpos+=8; }
            repaint();
            try {
                Thread.sleep(20);
            }
            catch (InterruptedException ex){
            }
        }
    }
}`
user1920076
  • 103
  • 1
  • 1
  • 14

1 Answers1

2

Basically you need to raise a flag when the key is pressed and reset it when it is released.

Then, in you main game loop, you need to check what flags are set and take appropriate action. This will eliminate the need for you to worry about the inherent delay between key events, which might be different on different platforms.

For an example, see Problems with Java's Paint method, ridiculous refresh velocity.

This allows the game object to be accelerated (and decelerated) over a small period of time based on the acceleration key.

Also, as has already being suggest, you should avoid KeyListener and use Key Bindings, mostly because you will run into focus issues with KeyListerner

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366