Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
keyboard input problem Posted by jenia2009 on 29 Jun 2010 at 2:50 PM
I'm programming a little Mario game.
Now when the player is pressing left, the character is running left.
Now lets say the players press's up to jump. That immediately disables the left button that the player is still holding. Which is the problem.
Here is how I programed the keys

addKeyListener(new KeyListener() {

public void keyPressed(KeyEvent arg0) {
int key=arg0.getKeyCode();
if(key==KeyEvent.VK_LEFT){
mario.moveLeft();
}else if(key==KeyEvent.VK_RIGHT){
mario.moveRight();
}else if(key==KeyEvent.VK_UP){
mario.startJumpSequence();
}else if(key==KeyEvent.VK_END){
running=false;
}
}
});

So how can I make Mario move left when the player presses left, but when the player presses up (still holding left) mario jumps and moves left?

Just to recap, I'm pressing left for Mario to move left. Now i want to jump as im moving left; as soon as I hit the up key, mario jumps but "forgets" to move left even though i never release "left".
How to fix this?

Thank you for your time and help in advance
jenia
Report
Re: keyboard input problem Posted by anthrax11 on 29 Jun 2010 at 3:27 PM
You need to save the state of the movement.

For example, when the left key is pressed, then do something like "movingLeft = true". When the left key is released (you should override keyReleased in the KeyListener), then do "movingLeft = false".

If you do this for every key, then you know exactly which keys are pressed at the moment. Then, every time you update Mario's position, you can check these variables, so your periodically updated game loop would look something like this:
if(movingLeft){
  mario.moveLeft();
}
if(movingRight){
  mario.moveRight();
}

Well, that's the general idea. I hope it helps!



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.