I'm trying to make a character move around on a simple frame when the user presses the four arrow keys (or wasd). The character should continue to move as long as the arrow key is held down and should cease movement once the user has released the key.
For the most part, this is moving. However, I am getting some strange delay when rapidly switching directions. It looks as though, when I press the keyboard button, java's keylistener interprets this as a key "click", AKA rapid pressing and releasing, before determining that the button is actually being held down.
As such, the player model stutters in its motion a little bit.
Am I interpreting this correctly? Here is my code, if anyone can make sense of this.
Code to handle a key release
@Override
public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
GameController.hero.stopMoving();
break;
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_ESCAPE:
break;
}
keyPress = false;
}
My code to handle a key press
@Override
public void keyPressed(KeyEvent e)
{
keyPress = true;
keyCode = e.getKeyCode();
switch(e.getKeyCode())
{
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
GameController.hero.setSpeedBase(new Point(0,-1));
break;
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
GameController.hero.setSpeedBase(new Point(-1,0));
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
GameController.hero.setSpeedBase(new Point(0,1));
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
GameController.hero.setSpeedBase(new Point(1,0));
break;
}
}
I hope this is enough information. Any help is appreciated! Let me know if there is any clarification I can make. Is there an easier way to do this?
It's an old post, but for future folk that may visit this page, here is my answer
The KeyListener handles a key press as a text editor. When you hold a key, you will notice there is a delay before the editor starts repeating it.
To make a game in Java, we generally make another thread to handle input, the KeyListener just changes some flags that are checked on the game loop
I've made a video on this some time ago, the captions are in portuguese, but the code is in there at a visible font size.
https://www.youtube.com/watch?v=f7M9eAkNS8s
Best regards.