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

2016/5/15

Jumping error

kcrumpet kcrumpet

2016/5/15

#
I'm following a tutorial on youtube for jumping, but I'm having an issue where the player actor just teleports to the jump position instead of slowly going to it. This is my source code.
public class player extends Actor
{
    private int vSpeed = 0; //vertical speed, falling
    private int acceleration = 2; //fall faster when higher up
    private boolean jumping; //checks if the player is jumping or not
    private int jumpStrength = 100; //how high player jumps
    
    public void act() 
    {
        checkFall();
        checkKey();
    }
    
    public void checkKey(){
        if(Greenfoot.isKeyDown("z") && jumping == false)
        {
            jump();
        }
    }
    
    public void fall(){
        setLocation(getX(), getY() +vSpeed);
        if(vSpeed <=9)
        {
            vSpeed = 2 + acceleration; //if character is high up then fall faster
        }
        jumping = true; //stops you jumping while falling
    }
    
    public boolean onGround(){
        int spriteHeight = getImage().getHeight();
        int groundFind = (int)(spriteHeight/2) + 5;
        
        Actor ground = getOneObjectAtOffset(0, groundFind, platform.class);
        
        if(ground == null)
        {
            jumping = true; //stops jumping will not on ground
            return false;
        }
        else
        {
            moveToGround(ground); //passing our ground variable to our function
            return true;
        }
    }
    
    public void moveToGround(Actor ground){
        int groundHeight = ground.getImage().getHeight();
        int newY = ground.getY() - (groundHeight + getImage().getHeight())/2; //get ground height and add it to image of character then divide by 2
        
        setLocation(getX(), newY); //sets player location to our new calculated y location
        jumping = false; //ready to jump
    }
    
    public void checkFall(){
        if(onGround())
        {
            vSpeed = 0;
        }
        else
        {
            fall();
        }
    }
    
    public void jump(){
        vSpeed = vSpeed - jumpStrength;
        jumping = true;
        fall();
    }
}
Meh Meh

2016/5/15

#
replace lines 23 - 26 with
vSpeed = vSpeed + acceleration;
and jumpStrength shouldn't be that high (20 is better)
You need to login to post a reply.