Friday, January 10, 2014

Platformer: Adding Movement

Now that we have our player "falling" and landing on platforms and jumping, it's time to add some left & right motion.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Player here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Player extends Actor
{
    private int vSpeed = 0;
    private int acceleration = 1;
    private boolean jumping;
    private int jumpStrength = 16;
    private int speed = 4;
    
    /**
     * Act - do whatever the Player wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        checkFall();
        checkKey();
    }   
    
    public void checkKey()
    {
        if(Greenfoot.isKeyDown("space") && jumping == false)
        {
            jump();
        }
        if(Greenfoot.isKeyDown("right"))
        {
            moveRight();
        }
        if(Greenfoot.isKeyDown("left"))
        {
            moveLeft();
        }
    }
    
    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()
    {
        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
        {
            moveToGround(ground);
            return true;
        }
    }
    
    public void moveToGround(Actor ground)
    {
        int groundHeight = ground.getImage().getHeight();
        int newY = ground.getY() - (groundHeight + getImage().getHeight())/2;
        setLocation(getX(), newY);
        jumping = false;
    }
    
    public void checkFall()
    {
        if(onGround())
        {
            vSpeed = 0;
        }
        else
        {
            fall();
        }
    }
    
    public void jump()
    {
        vSpeed = vSpeed - jumpStrength;
        jumping = true;
        fall();
    }
}

No comments:

Post a Comment