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

2016/11/2

Jump Once per Key Press

gmacias gmacias

2016/11/2

#
Hello, I am trying to make this player jump only once per key press. I find that if I hold down the key (space key), it jumps over and over. I want it to jump once and fall regardless if I let go of the key. I am thinking I need to add another if-statement but not sure how to code. Your help is appreciated. Thank you...
public class Willa extends AnimatedActor
{
    private int vSpeed = 0;
    private int acceleration = 1;
    private int jumpHeight = -12;  // how high to jump
    /**
     * Act - do whatever the Willa wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        control();
        checkFalling();
    }    
    
    private void control()
    {
        if (Greenfoot.isKeyDown("right"))
        {
            animate (4,5);
        }
        if (Greenfoot.isKeyDown("left"))
        {
            animate (2,3);
        }
        if (Greenfoot.isKeyDown("space")&& (onGround() == true))
        {
            vSpeed = jumpHeight;
            fall();
        }
    }
    
    private void fall()
    {
        setLocation(getX(),getY()+ vSpeed);
        vSpeed = vSpeed + acceleration;
    }
    
    private boolean onGround()
    {
        Actor under = getOneObjectAtOffset(0,getImage().getHeight()/2,Ground.class);
        return under != null;
    }
    
    private void checkFalling()
    {
        if (onGround() == false)
        {
            fall();
        }
    }

}
danpost danpost

2016/11/2

#
gmacias wrote...
I am thinking I need to add another if-statement but not sure how to code.
Another if statement will not do -- or, at least, not be enough. You will need to track the state of the space key from act cycle to act cycle. To retain that state, you need an instance boolean field -- call it 'spaceDown'. With the field, you will be able to detect any change in state -- the key being pressed and the key being released. Then you can have the actor jump only when the key is pressed:
// with instance field
private boolean spaceDown;

// in act or method it calls
if (spaceDown != Greenfoot.isKeyDown("space")) // change detection (any)
{
    spaceDown = ! spaceDown; // record change
    if (spaceDown && onGround()) // is new state down and actor on ground
    // etc.
gmacias gmacias

2016/11/2

#
Ok, thank you!
You need to login to post a reply.