Jump to content
  • Advertisement
Sign in to follow this  
c4nux0r

[java] Handling Multiple Key presses at once

This topic is 4873 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am having troubles being able to handle pressing more than one key at once, I am trying to get it so that if the user presses up and left for example then the player will move up and left, however so far all I can get it to do is go the dirrection of the last pressed key, if anyone could help that would be great Thanks

Share this post


Link to post
Share on other sites
Advertisement
Try something like this:


boolean moveUp = false;
boolean moveRight = false;

...

addKeyListener(new KeyListener(){

public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == UP_KEY)
moveUp = true;
if(e.getKeyCode() == RIGHT_KEY)
moveRight = true;
}

public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == UP_KEY)
moveUp = false;
if(e.getKeyCode() == RIGHT_KEY)
moveRight = false;
}

public void keyTyped(KeyEvent e){}

});

...

movePlayer()
{
if(UP_KEY)
player.y++;
if(RIGHT_KEY)
player.x++;
}


This is of course, assuming you handle input with key listeners. They are an event-driven system of input, which means you're only going to get the last processed event at any given time. Using flags for up/down/left/right is the best way to get around this.

I could be wrong however. I ditched KeyListeners a long time ago when I switched to LWJGL and its wonderful dead-simple input class. I'd recommend looking into it unless you're stuck on another library.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!