2

I have the following code snippet from my SWING game:

public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_RIGHT)
        {         
             player.setX(player.getX() + speed);
             canvas.repaint();

        }

The code is working correctly, when I press the right arrow(VK_RIGHT), the player moves RIGHT, if I press the left arrow it moves left.

The problem is when I hold the LEFT or RIGHT arrow, the player moves once and then it stops for some time and then it starts continuously moving the pressed direction.

I think it takes time for java to understand that the pressed button is HOLD. Any idea how I can make it move continuously instantly?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
CuriousGuy
  • 1,545
  • 3
  • 20
  • 42
  • 1
    Please provide some code which reproduces the problem . With your code above, we can't give you the right answer. – Kami Jul 29 '15 at 21:26
  • Do you mean when you press the arrow "key", cause this gets asked quite a bit – MadProgrammer Jul 29 '15 at 21:29
  • Edited the description of my question – CuriousGuy Jul 29 '15 at 21:32
  • 2
    Looks like a similar question [link](http://gamedev.stackexchange.com/questions/56017/java-best-implementation-keylistener-for-games). Probably the second answer can solve your problem. – Vladimir Jul 29 '15 at 21:36
  • 2
    That is caused by how your keyboard works - when you press down on a key, it causes a key event. After a short time lag with the key still held down, some (not all) keyboards will begin issuing a continuous stream of button press events until the button is released. – FredK Jul 29 '15 at 21:42
  • You need a flag to indicate which keys are pressed and background thread or timer which can repeatedly check the state of these flags and update the state of your objects, for [example](http://stackoverflow.com/questions/28423393/how-to-get-a-rectangle-to-stop-when-you-release-a-key-that-moves-it/28423725#28423725), [example](http://stackoverflow.com/questions/22748547/java-swing-timer-only-works-once-then-keyevents-fire-in-rapid-succession-holdi/22749251#22749251), [example](http://stackoverflow.com/questions/16328946/java-keylistener-stutters/16329029#16329029) – MadProgrammer Jul 29 '15 at 22:04
  • 2
    To emphasize this: This is not related to Java or Swing. Just press a key and hold it in any text editor: aaaaaaaaaaaaaaa.... Sometimes you can even set the delay and speed in the BIOS. Anyhow, the linked answers should help to solve this. – Marco13 Jul 29 '15 at 22:07

1 Answers1

1

Any idea how I can make it move continuously instantly?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433