This site requires JavaScript, please enable it in your browser!
Greenfoot back
dark_sky
dark_sky wrote ...

2012/5/5

Key Pressing

dark_sky dark_sky

2012/5/5

#
Hello everyone, I started working with Greenfoot a few days ago and I'm wondering if there's no possibility to check whether a key a was pressed once, not whether it is pressed. I developed a little game in which an Actor can jump up by pressing the up key (Greenfoot.isKeyPressed("up")), but if I hold it down, my Actor is flying and this is definitely not what I want. Would be nice if you could help me to solve this problem. Thank you
erdelf erdelf

2012/5/5

#
Use
(Greenfoot.isKeyDown("up"))
danpost danpost

2012/5/5

#
@erdelf, isKeyDown will continue to be true as long as the key is down (not what dark_sky wants) @dark_sky, there is another Greenfoot command, called getKey(); use
String key = Greenfoot.getKey();
if (key != null && key.equals("up")) jump();
You may also want to add an instance actor boolean variable jumping (initially set to false). Set it to true within jump(). When to actor finds something to stand on again, reset it to false. Add to the if statement above '&& !jumping'.
dark_sky dark_sky

2012/5/5

#
@danpost Thank you very much for your help!
dark_sky dark_sky

2012/5/5

#
One last question: is it possible to make the actor jump when starting to press the button? If I do it like you told me, it starts jumping when I stop pressing the key :x
danpost danpost

2012/5/5

#
Yes, but you must use a boolean to prevent flying (the canJump() method below should return a boolean)! Go back to using the isKeyDown method and drop the 'jumping' boolean and add one called 'upPressed'; set to true when 'up' key is found down, set to false when key is released. Use it in conjunction with finding standing ground to aid in timing of reset of jumping.
if (!upPressed && Greenfoot.isKeyDown("up") && canJump())
{
    upPressed = true;
    jump();
}
if (upPressed && !Greenfoot.isKeyDown("up")) upPressed = false;
where canJump() will check to make sure the actor is standing on something.
You need to login to post a reply.