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

2013/4/23

How to change the image upon different key press for an actor? SetImage and GetImage help

nathan1610 nathan1610

2013/4/23

#
My current code if (Greenfoot.isKeyDown("right")) { move(1); } else if (Greenfoot.isKeyDown("left")) { move(-1); } else if (Greenfoot.isKeyDown("up")) { setLocation(getX(), getY()-1); } else if (Greenfoot.isKeyDown("down")) { setLocation(getX(), getY()+1); } How do i integrate a different image for each movement? I have four images in the Images file Left = left.png Right= right.png Up= back.png Down= Person2.png Thank you for help!
Gevater_Tod4711 Gevater_Tod4711

2013/4/23

#
In Greenfoot almost every image you use is a GreenfootImage so you should create GreenfootImages of all the images you want to use:
private GreenfootImage left = new GreenfootImage("left.png");
private GreenfootImage right= new GreenfootImage("right.png");
private GreenfootImage up= new GreenfootImage("back.png");
private GreenfootImage down= new GreenfootImage("Person2.png");
If you got this images in your class you just need to change the images like this:
if (Greenfoot.isKeyDown("right")) {
    move(1);
    setImage(right);
}
else if (Greenfoot.isKeyDown("left")) {
    move(-1);
    setImage(left);
}
else if (Greenfoot.isKeyDown("up")) {
    setLocation(getX(), getY()-1);
    setImage(up);
}
else if (Greenfoot.isKeyDown("down")) {
    setLocation(getX(), getY()+1);
    setImage(down);
}
You need to login to post a reply.