protected int speed;
Next, we will add some move methods.protected int speed;
/**
* Move an object to the right
*/
protected void moveRight()
{
setLocation (getX() + speed, getY());
}
/**
* Move an object to the left
*/
protected void moveLeft()
{
setLocation (getX() - speed, getY());
}
Next we want to adjust the Mario class so that he idles facing left or right:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Mario here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Mario extends Mover
{
private final GreenfootImage idleRight = new GreenfootImage("mario-idle.gif");
private final GreenfootImage idleLeft = new GreenfootImage(idleRight);
public Mario()
{
this.speed = 7;
setImage(idleRight);
idleRight.scale(38,50);
idleLeft.scale(38,50);
idleLeft.mirrorHorizontally();
}
/**
* Act - do whatever the Mario wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
checkKeys();
}
/**
* This method checks which key has been pressed and then responds with an action.
*/
private void checkKeys()
{
if (Greenfoot.isKeyDown("right"))
{
walkRight();
}
else if (Greenfoot.isKeyDown("left"))
{
walkLeft();
}
}
/**
* Moves Mario right and applies the right-facing images.
*/
private void walkRight()
{
moveRight();
setImage(idleRight);
}
/**
* Moves Mario left and applies the left-facing images.
*/
private void walkLeft()
{
moveLeft();
setImage(idleLeft);
}
}
No comments:
Post a Comment