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;
private GreenfootImage run1r = new GreenfootImage("run1r.png");
private GreenfootImage run2r = new GreenfootImage("run2r.png");
private GreenfootImage run3r = new GreenfootImage("run3r.png");
private GreenfootImage run4r = new GreenfootImage("run4r.png");
private GreenfootImage run1l = new GreenfootImage("run1l.png");
private GreenfootImage run2l = new GreenfootImage("run2l.png");
private GreenfootImage run3l = new GreenfootImage("run3l.png");
private GreenfootImage run4l = new GreenfootImage("run4l.png");
private int frame = 1;
private int animationCounter = 0;
/**
* 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();
animationCounter++;
}
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());
if(animationCounter % 4 == 0)
{
animateRight();
}
}
public void animateRight()
{
if(frame == 1)
{
setImage(run1r);
}
else if(frame == 2)
{
setImage(run2r);
}
else if(frame == 3)
{
setImage(run3r);
}
else if(frame == 4)
{
setImage(run4r);
frame = 1;
return;
}
frame++;
}
public void moveLeft()
{
setLocation(getX()-speed, getY());
if(animationCounter %4 == 0)
{
animateLeft();
}
}
public void animateLeft()
{
if(frame == 1)
{
setImage(run1l);
}
else if(frame == 2)
{
setImage(run2l);
}
else if(frame == 3)
{
setImage(run3l);
}
else if(frame == 4)
{
setImage(run4l);
frame = 1;
return;
}
frame++;
}
public void fall()
{
setLocation(getX(), getY() + vSpeed);
if(vSpeed <=9)
{
vSpeed = vSpeed + acceleration;
}
jumping = true;
}
public boolean onGround()
{
int spriteHeight = getImage().getHeight();
int yDistance = (int)(spriteHeight/2) + 5;
Actor ground = getOneObjectAtOffset(0, getImage().getHeight()/2, 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();
}
}
Monday, January 13, 2014
Platformer: Animated Player Sprite
Today we added our player sprites and animated them:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment