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

2020/1/25

How to add gravity when you only jump

SPIDERVERSEE SPIDERVERSEE

2020/1/25

#
Hello, Do you guys know how to code gravity so that, it will only be in use when you actually jump? And that it will fall to the place where you jumped? I made a game like crossy road, but I don't know how to code the jump. I will be so gratefull if someone would respond! My coding so far is:
 
public class Jumper extends Actor
{
    private int ySpeed;
 
    public Jumper()
    {
    }
 
    public void act()
    {
        int groundLevel = getWorld().getWidth() - getImage().getHeight()/2;
        boolean onGround = (getY() == groundLevel);
        if (!onGround) // in middle of jump
        {
            ySpeed++; // adds gravity effect
            setLocation(getX(), getY()+ySpeed); // fall (rising slower or falling faster)
            if (getY()>=groundLevel) // has landed (reached ground level)
            {
                setLocation(getX(), groundLevel); // set on ground
                Greenfoot.getKey(); // clears any key pressed during jump
           }
        }
        else // on ground
        {
            if ("space".equals(Greenfoot.getKey())) // jump key detected
            {
                ySpeed = -15; // add jump speed
                setLocation(getX(), getY()+ySpeed; // leave ground
            }
        }
    }
}
danpost danpost

2020/1/26

#
SPIDERVERSEE wrote...
Do you guys know how to code gravity so that, it will only be in use when you actually jump? And that it will fall to the place where you jumped? I made a game like crossy road, but I don't know how to code the jump.
Instead of getKey, use isKeyDown with a boolean field to track the state of the "space" key. That way, you can regulate it so that the key is released between each jump.
You need to login to post a reply.