Page 1 of 2 12 LastLast
Results 1 to 20 of 26
  1. #1
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default KeyBindings for a Game

    I'm making a game which lets the player move around with arrow keys, but my KeyListeners are working less-than-satisfactorily. I googled this and I found that I should use KeyBindings. I read a few different tutorials, and I'm still confused.

    1) Right now I have booleans for each key used in the game. When a key is pressed, the boolean is set to true, and set to false when it is released. In the ActionListener for the Timer I have, I then check if each is pressed or not, and do the corresponding action. I do this so that movement is smooth.
    If I was to use KeyBindings, would I use the same technique, or would I just do the action in their Action?

    2) How do I do it? From the example I thought was most helpful, this is my guess: (this code would be in a JPanel)
    Java Code:
    this.getInputMap().put(  KeyStroke.getKeyStroke( "ENTER" ) , "doEnterAction"  );
    this.getActionMap().put(  "doEnterAction" , EnterAction );
    
    static class EnterAction extends AbstractAction
        {
            public void actionPerformed( ActionEvent tf )
            {
                enterKeyIsPressed=true; //If using this method, I would also have a separate InputMapping, ActionMapping,
                                      //and Action for EnterButtonRelesed
               //OR
    
               moveRight(); //whatever that key should do
            }
        }
    How does this look?
    Last edited by Prime624; 01-26-2014 at 06:01 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: KeyBindings for a Game

    How does this look?
    Have you tried writing, compiling and executing the code? What happened?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    It doesn't work because it says EnterAction doesn't exist. Do I need to create an instance of each action as well?

    Also, what do you think about question 1 in the original post?

    EDIT: Right now, I'm trying the following in my code:
    Java Code:
       public MyJPanel() {
    
            //other code
    
            this.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"up");
            this.getActionMap().put("up",upAction);
        }
        public static class upAction extends AbstractAction {public void actionPerformed(ActionEvent e){System.out.println("enter pressed");}}
    Last edited by Prime624; 01-26-2014 at 06:00 PM.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,656
    Blog Entries
    7
    Rep Power
    21

    Default Re: KeyBindings for a Game

    Quote Originally Posted by Prime624 View Post
    It doesn't work because it says EnterAction doesn't exist. Do I need to create an instance of each action as well?

    Also, what do you think about question 1 in the original post?

    EDIT: Right now, I'm trying the following in my code:
    Java Code:
       public MyJPanel() {
    
            //other code
    
            this.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"up");
            this.getActionMap().put("up",upAction);
        }
        public static class upAction extends AbstractAction {public void actionPerformed(ActionEvent e){System.out.println("enter pressed");}}
    Yep, you have to use an instance of your class, not the class itself; the entire setup looks sensible to me ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    Ok. I got it working, but it looks very wrong. The following code is just for the four arrow keys. All it does is set the key's respective boolean to true or false, depending on if the key was pressed of released.

    I have this in the constructor:
    Java Code:
            UP_ARROW_ACTION upActionInstance=new UP_ARROW_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("UP"),"up pressed");
            this.getActionMap().put("up pressed",upActionInstance);
            UP_ARROW_RELEASED_ACTION upReleasedActionInstance=new UP_ARROW_RELEASED_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("released UP"),"up released");
            this.getActionMap().put("up released",upReleasedActionInstance);
            DOWN_ARROW_ACTION downActionInstance=new DOWN_ARROW_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("DOWN"),"down pressed");
            this.getActionMap().put("down pressed",downActionInstance);
            DOWN_ARROW_RELEASED_ACTION downReleasedActionInstance=new DOWN_ARROW_RELEASED_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("released DOWN"),"down released");
            this.getActionMap().put("down released",downReleasedActionInstance);
            LEFT_ARROW_ACTION leftActionInstance=new LEFT_ARROW_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),"left pressed");
            this.getActionMap().put("left pressed",leftActionInstance);
            LEFT_ARROW_RELEASED_ACTION leftReleasedActionInstance=new LEFT_ARROW_RELEASED_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("released LEFT"),"left released");
            this.getActionMap().put("left released",leftReleasedActionInstance);
            RIGHT_ARROW_ACTION rightActionInstance=new RIGHT_ARROW_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"),"right pressed");
            this.getActionMap().put("right pressed",rightActionInstance);
            RIGHT_ARROW_RELEASED_ACTION rightReleasedActionInstance=new RIGHT_ARROW_RELEASED_ACTION();
            this.getInputMap().put(KeyStroke.getKeyStroke("released RIGHT"),"right released");
            this.getActionMap().put("right released",rightReleasedActionInstance);
    And this below the constrcutor: (I broke it up so it's easier to read, although there's not much it does)
    Java Code:
    public class UP_ARROW_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){UP_ARROW_KEY=true;}}
    
    public class UP_ARROW_RELEASED_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){UP_ARROW_KEY=false;}}
    
    public class DOWN_ARROW_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){DOWN_ARROW_KEY=true;}}
    
    public class DOWN_ARROW_RELEASED_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){DOWN_ARROW_KEY=false;}}
    
    public class RIGHT_ARROW_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){RIGHT_ARROW_KEY=true;}}
    
    public class RIGHT_ARROW_RELEASED_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){RIGHT_ARROW_KEY=false;}}
    
    public class LEFT_ARROW_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){LEFT_ARROW_KEY=true;}}
    
    public class LEFT_ARROW_RELEASED_ACTION extends AbstractAction {
    public void actionPerformed(ActionEvent e){LEFT_ARROW_KEY=false;}}
    That's a heck of a lot of code for four keys. Am I doing something wrong?
    Last edited by Prime624; 01-26-2014 at 06:41 PM.

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,656
    Blog Entries
    7
    Rep Power
    21

    Default Re: KeyBindings for a Game

    I'd go for your second option, i.e. let your ActionHandlers handle the stuff themself; why re/set a boolean value and let yet another method figure out what to do? The ActionHandler already knows what to do ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    I tried doing that, but the game seemed to "lag" like it would with KeyListeners. The moment the button is pressed, it moves, then waits, then moves at a consistent pace . I want it to move at a consistent pace from the moment it is pressed.

    But I am doing everything else right?

    BTW, thank you for your help.

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: KeyBindings for a Game

    I want it to move at a consistent pace
    What code changes its position and displays it at the new position?
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    Quote Originally Posted by Norm View Post
    What code changes its position and displays it at the new position?
    The Timer's ActionListener. I say "if aKey then move left and repaint".

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: KeyBindings for a Game

    Hard to say why the motion waits without being able to execute the code.
    Have you tried debugging the code by adding some println statements that print the current time to show where the wait time is lost?
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    It's lagging in the same way that KeyListeners lag. At least that's how it appears outwardly.

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,782
    Rep Power
    5

    Default Re: KeyBindings for a Game

    It seems like this is a round-a-bout way of moving something. Why do you use a timer? Using a KeyListener to move something around the screen is relatively trivial. There must be something going on here that you haven't explained.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    Quote Originally Posted by jim829 View Post
    It seems like this is a round-a-bout way of moving something. Why do you use a timer? Using a KeyListener to move something around the screen is relatively trivial. There must be something going on here that you haven't explained.

    Regards,
    Jim
    The game right now is just moving a guy around a map and vaporizing (deleting) trees with spacebar. I have been using KeyListeners with booleans to avoid lag. I just recently tried to make it so that if shift is held down, the man will move faster. It didn't work, and I was told (for the third time since starting this game) that I should instead use KeyBindings for anything more complex than shortcut keys.

    EDIT: Why I don't just use a KeyListener is because it lags like described above. In my Com Sci class, we were taught to use booleans and a Timer to move characters in games to avoid the lag.

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: KeyBindings for a Game

    Can you explain the sequence of events?
    I was assuming that a key press started the motion and the motion continued until the key was released. Sort of like the when a key is held down in a text input area: the letter is printed until the key is released. Two events: press and release. To continue the motion, there needs to be a Timer that changes the position and calls repaint().
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,782
    Rep Power
    5

    Default Re: KeyBindings for a Game

    Quote Originally Posted by Prime624 View Post
    and I was told (for the third time since starting this game) that I should instead use KeyBindings for anything more complex than shortcut keys.
    Actually, I would think the opposite is true since KeyListeners are a more low level interface. If I want to do something with any key being pressed, I would use a keylistener. But for simple matters like short cuts, I would use keyBindings. But I don't get the lag issue between the two.

    So I assume you are letting the timer take over to increment the position while the key is pressed and then backing off when the key is released, correct?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  16. #16
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    Quote Originally Posted by Norm View Post
    Can you explain the sequence of events?
    I was assuming that a key press started the motion and the motion continued until the key was released. Sort of like the when a key is held down in a text input area: the letter is printed until the key is released. Two events: press and release. To continue the motion, there needs to be a Timer that changes the position and calls repaint().
    That's exactly correct. Try holding down a key in the url bar though. It doesn't enter the same amount of keys per second from the start. It enters one, hesitates, then enters more at a consistent rate. I don't want the game character taking a step then waiting then running whenever the player presses the arrow key.

  17. #17
    Prime624 is offline Member
    Join Date
    Feb 2013
    Location
    San Diego
    Posts
    96
    Rep Power
    0

    Default Re: KeyBindings for a Game

    Quote Originally Posted by jim829 View Post
    Actually, I would think the opposite is true since KeyListeners are a more low level interface. If I want to do something with any key being pressed, I would use a keylistener. But for simple matters like short cuts, I would use keyBindings. But I don't get the lag issue between the two.

    So I assume you are letting the timer take over to increment the position while the key is pressed and then backing off when the key is released, correct?

    Regards,
    Jim
    You are correct. And by shortcuts, I meant complicated ones involving more than two keys.

  18. #18
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,782
    Rep Power
    5

    Default Re: KeyBindings for a Game

    I got it working with key listeners. But you are correct about the lag. But I don't know if it's key listeners or not. It is a lag for determining whether the user is actually holding down the key or just not releasing it fast enough. The shift also works to speed it up. I assume you are using the Swing Timer. When the user types a shift you can reset the timer value to lower delay. You can also modify the x/y increment values to make it appear to move faster.

    Next I'll try it with KeyBinding to see if behaves similarly.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  19. #19
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,782
    Rep Power
    5

    Default Re: KeyBindings for a Game

    Well, I did this key bindings but I saw no improvement in responsiveness. I would do this with KeyListener simply because it is much easier to set up by requiring signficantly less code.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,563
    Rep Power
    25

    Default Re: KeyBindings for a Game

    It enters one, hesitates, then enters more at a consistent rate.
    That sounds like an OS setting for handling key presses. The OS sends multiple key presses while a key is being held down.
    Does the code use those key pressed events, or does it just use the first key press and wait for the key released event?
    If you don't understand my response, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. SWING keybindings
    By JavaJimme in forum AWT / Swing
    Replies: 6
    Last Post: 11-26-2013, 09:03 AM
  2. Unresponsive keybindings
    By Insomniac.. in forum AWT / Swing
    Replies: 5
    Last Post: 07-21-2013, 06:50 PM
  3. keybindings
    By jsobel in forum New To Java
    Replies: 8
    Last Post: 04-03-2012, 04:41 PM
  4. KeyBindings Empty Key?
    By Unome in forum Java Applets
    Replies: 1
    Last Post: 10-24-2008, 07:28 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •