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

2015/7/24

How to get an image to go back to original once changed.

JamesHughes JamesHughes

2015/7/24

#
private GreenfootImage snake_attack = new GreenfootImage("SnakeEnemyAttack.png");
    private GreenfootImage snake = new GreenfootImage("SnakeEnemy.png");
    
    public void act() 
    {
        if(Greenfoot.isKeyDown("space")){
        setImage(snake_attack);}
    }    
}
above is my code, when i press space it changes the image, but i want it to go back to the original image when space is released. Please make it as simple as possible as i am only a beginner. Thanks in advance.
Super_Hippo Super_Hippo

2015/7/24

#
The simplest way to do it would be to add this line after line 7:
else setImage(snake);
This will set the image every act cycle no matter if it is needed or not. To avoid that, you could look at the following code. It only changes the image if the change is needed.
private GreenfootImage[] snake = {new GreenfootImage("SnakeEnemy.png"), new GreenfootImage("SnakeEnemyAttack.png")};
private int currentImage = 0;
private int nextImage = 0;

public void act() 
{
    if (Greenfoot.isKeyDown("space")) nextImage = 1;
    else nextImage = 0;
    
    if (currentImage != nextImage)
    {
        setImage(snake[nextImage]);
        currentImage = nextImage;
    }
}
You need to login to post a reply.