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

2014/4/9

Actor only jumps once

Greenfootnoob Greenfootnoob

2014/4/9

#
My actor can only jump once. can anyone help me with making the actor continously when i hold down the space bar?
public class man extends Animal
{
    private int vSpeed = 0;
    private int acceleration = 2; 
    private boolean jumping;
    private int jumpStrenght= 20;
    private int speed= 4;

    public void act() 
    {
        checkFall();
        checkKeys();
    }
    
    public void checkKeys()
    {
        if(Greenfoot.isKeyDown("space") && jumping == false)
        {
            jump();
        }
        
        if(Greenfoot.isKeyDown("right"))
        {
            move(5);
        }
        
        if(Greenfoot.isKeyDown("left"))
        {
            move(-5);
        }
    }

    
    public void fall()
    {
        setLocation(getX(), getY()+vSpeed);  

        vSpeed = vSpeed + acceleration;  
        jumping= true;
    }

    public boolean onGround()
    {
        int spriteHeight= getImage().getHeight();
        int LookForGround= (int) (spriteHeight/2) + 5;

        Actor ground= getOneObjectAtOffset(0, LookForGround, Platform.class);

        if(ground == null)
        {
            jumping = true;
            return false;
        }
        else
        {
            return true;
        }
    }

    public void checkFall()
    {
        if(onGround())
        {
            vSpeed = 0;
        }
        else
        {
            fall(); 
        } 
    }
    
    public void jump()
    {
        vSpeed= vSpeed- jumpStrenght;
        jumping = true;
        fall();
         if(Greenfoot.isKeyDown("space") && jumping == false)
        {
            jump();
        }
    }
}
danpost danpost

2014/4/9

#
I do not understand why there is a need for both the 'onGround' boolean AND the 'jumping' boolean. Does not the following always hold true? onGround == !jumping or this? jumping == !onGround Having both fields just complicates matters. Anyways, I did not see anywhere in the code where 'jumping' is set back to 'false'; so, the condition on line 17 will not ever again be 'true'. Thus, only jumps once.
You need to login to post a reply.