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

2012/5/8

jumping on keypress

dark_sky dark_sky

2012/5/8

#
Hello everyone, I'm just coding a little platforming game and I'm using
if("up".equals(Greenfoot.getKey()) && jumping == false) { jump(); }
to let my player character jump. Only problem with this is that the player jumps when I stop pressing the key and I can't figure out how to make it jump when the player starts pressing the up key. I'd be glad if you could help me solve this problem!
davmac davmac

2012/5/8

#
Need to see more code. What does 'jump()' do?
danpost danpost

2012/5/8

#
You will need to use 'Greenfoot.isKeyDown("up")' instead of '"up".equals(Greenfoot.getKey()'. However, you will also need to add a boolean 'upKeyDown', initially set to 'false'. Set it to true when the key is found pressed, and add a check 'if (upKeyDown && !Greenfoot.isKeyDown("up")) upKeyDown = false;' (that way, each initial press of the key will trigger jump).
davmac davmac

2012/5/8

#
ah, good catch danpost. That most likely is the problem.
matt.milan matt.milan

2012/5/8

#
only problem is that you'll be able to jump if you're in the air. add a check to see if you're on the ground first, or to check how many jumps you can make the check:
/** insert into field
private final int MAX_JUMPS = 2;
private int jumpsLeft = MAX_JUMPS;
private int jumpsMade = 0;

/**insert into keyChecking method
if (Greenfoot.isKeyDown("up") && onGround() && !upKeyDown)
{
    jumpsMade = MAX_JUMPS;
    upKeyDown = true;
    jump();
}
else upKeyDown = false;
the onGround method:

public boolean onGround()
{
    if (jumpsMade < jumpsLeft)
    {
        jumpsMade++;
        return true;
    }
    else
    {
        return getOneObjectAtOffset(getX(),getY() + getImage().getHeight() / 2,Platform.class) != null;
    }
}
dark_sky dark_sky

2012/5/9

#
I solved it like Danpost proposed it and it really works well. Thank you!
You need to login to post a reply.