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

2014/11/16

How to stop make my actor continuously going up when jumping?

JustAStudent JustAStudent

2014/11/16

#
My actor which is a cat, continuously goes up if you hold the space bar. How can I make it jump without it flying? Here's my code:
public class Cat extends Actor
{
   
    private int speed = 5;
    private int vSpeed = 0;
    private int acceleration = 1;
    private int jumpStrength = 5;
    private boolean jumping;
    public void act()
    {
        checkKeys();
        checkFall();
    }
    public void checkFall()
    {
        if(onGround()) 
        {
            vSpeed = 0;
        }
        else {
            fall();
        }
    }
   private void checkKeys()
    { 
        if(Greenfoot.isKeyDown("left"))
        { 
            setImage("CatLeft.png");
            moveLeft();
        }
        if(Greenfoot.isKeyDown("right"))
        {
            setImage("CatRight.png");
            moveRight();
        }
         if(Greenfoot.isKeyDown("space"))
        {
            jump();
        }
       
    }
    public void jump()
{
    vSpeed = -jumpStrength;
    fall();
    
}
     public void moveRight()
        {
            setLocation ( getX() + speed, getY() );
        }
        public void moveLeft()
        {
            setLocation ( getX() - speed, getY() );
        }
    public void fall()
     {
            setLocation ( getX(),getY() + vSpeed);
            if(vSpeed <=9)
            {
                vSpeed = vSpeed + acceleration;
            }
            jumping = true;
        }
        public boolean onGround()
        {
            Actor under = getOneObjectAtOffset (0, getImage().getHeight()/2, Platform.class);
            return under != null;
           
       }
}
Super_Hippo Super_Hippo

2014/11/16

#
Maybe you should only jump when you are on a platform.
if (onGround() && Greenfoot.isKeyDown("space"))
{
    jump();
}
JustAStudent JustAStudent

2014/11/16

#
Thanks for the help!
You need to login to post a reply.