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
}
}
}
}
