0

I am using keybinds, like this, for example the bottom arrow key:

public class Bottom extends AbstractAction {

private GameScreen gameScreen;

public Bottom (GameScreen p) {      
    this.gameScreen = p;
    this.gameScreen.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
            KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Bottom");     
}

@Override
public void actionPerformed(ActionEvent e) {
    this.gameScreen.getMovement().moveDown();
}

}

And then I detect them via movement.java:

public class Movement {

    private Player player;

    public Movement(Player p) {
        this.player = p;
    }

    public void moveRight() {
    }

    public void moveLeft() {
    }

    public void moveUp() {
    }

    public void moveDown() {
    }

    public void jump() {
        this.player.jump();
    }
}

and handled here:

public class Keybinds {

    private GameScreen panel;

    public Keybinds(GameScreen game) {
        this.panel = game;
        this.addKeybinds();
    }

    private void addKeybinds() {
        addKey("Bottom", new Bottom(this.panel));
        addKey("Space", new Space(this.panel));
    }

    private void addKey(String bind, AbstractAction a) {
        this.panel.getActionMap().put(bind, a);
    }

}

Anyway, the OS by default have a repeat timer for keys, so when I click on a key, it was 1.3 or so seconds and then continues repeating. I am trying to make a smooth walking for my game.

My game doesn't have running, just walking, but I am not sure how would I do this.

I can add walking queue so it adds what direction was requested & then a loop that loops through walking queues and does it, but when the keys will start to repeat every millisecond or something idk the repeat delay after the main delay, it will add so many walking queues that you know, my character will get so far away. I thought of adding a timer, so it can add new queue every 1 second or something, but how would I do this? or is there a better way of adding walking system?

Artemkller545
  • 979
  • 3
  • 21
  • 55

2 Answers2

1

Don't use a KeyListener. Swing was designed to be used with Key Bindings.

I thought of adding a timer,

Yes, you should be using a Timer so you are not dependent on the OS key repeat rate.

See Motion With the Keyboard for more information and an example that uses Key Bindings and a Timer.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

Edit: No need to explain when there is an explanation already. Check this thread.

Community
  • 1
  • 1
ArneHugo
  • 6,051
  • 1
  • 26
  • 47