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

2013/5/9

How Do I Animate An Actor?

guttridgeb guttridgeb

2013/5/9

#
I'm trying to get one of my actors to switch between a couple of images but I can't seem to get it right. Here is what I have so far.
private GreenfootImage image1;
    private GreenfootImage image2;

    public void act() 
    {
        image1 = new GreenfootImage ("turtle2.png");
        image2 = new GreenfootImage ("turtle1.png");
        setImage (image1);

        if (getImage() == image1)
        {
            setImage (image2);
        }
        else
        {
            setImage (image1);
        }
    }   
Any help is much appreciated :)
danpost danpost

2013/5/9

#
Line 8 will set the image to 'image1'. Then, line 10 will always be true; so line 12 will set the image to 'image2. Net result is the image will always appear to be 'image2'. What you need to do is initialize the images in the constructor of the class when the actor is created, not in the act method.
public Turtle()
{
    image1 = new GreenfootImage("turtle2.png");
    image2 = new GreenfootImage("turtle1.png");
    setImage(image1);
}

public void act()
{
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
}
Gevater_Tod4711 Gevater_Tod4711

2013/5/9

#
First you shouldn't load the GreenfootImages in the act method because this way they'll be loaded every act again and again. You better do it like this:
private GreenfootImage image1 = new GreenfootImage ("turtle2.png"); 
private GreenfootImage image2 = new GreenfootImage ("turtle1.png");  
The second problem is that you try to compare the two images using == but this only works for int, double, char, ... not for objects. So you better try this:
if (getImage().equals(image1)) {  
    setImage (image2);  
}  
else {  
    setImage (image1);  
}  
guttridgeb guttridgeb

2013/5/9

#
That's great, thank you!
danpost danpost

2013/5/9

#
Gevater_Tod4711 wrote...
The second problem is that you try to compare the two images using == but this only works for int, double, char, ... not for objects.
That is not exactly true. It does work for objects also, but they have to be the exact same object (referencing the same instance of a class). Look at the code I provided above, at all times after the constructor is executed, the set image IS either 'image1' or 'image2' and the checks for them will work. The problem occurs when you try to compare something like 'getimage()' with 'new GreenfootImage("turtle1.png")'. Even if the set image was that of 'image2' (which is created from the 'turtle1.png' file), the comparison will not be equal. The images are the same, but the objects are different. In other words, when using '==' with objects, read it as "is the same instance as".
You need to login to post a reply.