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

2023/5/2

How to make actor switch between two images

BigDogAlex BigDogAlex

2023/5/2

#
I'm trying to make my actor switch between tow images so it looks like it's moving but I can't get it to work.
danpost danpost

2023/5/2

#
BigDogAlex wrote...
I'm trying to make my actor switch between tow images so it looks like it's moving but I can't get it to work.
Can't help fix your code unless it is available. Please show attempted codes.
BigDogAlex BigDogAlex

2023/5/2

#
private GreenfootImage image1;
    private GreenfootImage image2;
    
    public static int speedOverTime = 0;
    public int health = 5;
    public void act() 
    {
        movement();
        damage();
        speedTime();
        speedOverTime++;
        image1 = new GreenfootImage("EvilCrabLeft.png");
        image2 = new GreenfootImage("EvilCrabRight.png");
        setImage(image1);
        walkAnimation();
    }
    /**
     * 
     */
    public void walkAnimation()
    {
        if(getImage() == image1)
        {
            setImage(image2);
        }
        else
        {
            setImage(image1);
        }
    }
danpost danpost

2023/5/2

#
BigDogAlex wrote...
<< Code Omitted >>
You are continuously setting the image to a NEW EvilCrabLeft image every act before attempting to change it. So, it is always image1 when trying to animate. Use a constructor method to initialize the image. The act method should only change the animation. You will also need an int animation timer. Without a timer, the images will change back and forth too quickly for both the scenario (skipped frames) and for your eye (visualizing). At normal scenario speed, an image in an animation should be visible for at least a few frames (4 or 5, minimum). Your code would then be something like this (assuming the class name is EvilCrab):
public static int speedOverTime = 0;


private GreenfootImage image1;
private GreenfootImage image2;
public int health = 5;
private int animTimer;
private int animFrames = 8;

public EvilCrab()
{
    image1 = new GreenfootImage("EvilCrabLeft.png");
    image2 = new GreenfootImage("EvilCrabRight.png");
    setImage(image1);
}

public void act() 
{
    movement();
    damage();
    speedTime();
    speedOverTime++;
    walkAnimation();
}

public void walkAnimation()
{
    animTimer = (animTimer+1)%animFrames;
    if (animTimer == 0)
    {
        if (getImage() == image1)
        {
            setImage(image2);
        }
        else
        {
            setImage(image1);
        }
    }
}
You will probably need an int timer for bumping the speedOverTime value as well.
BigDogAlex BigDogAlex

2023/5/2

#
Thank you for the help.
You need to login to post a reply.