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

2019/6/15

How to Switch Between Background Smoothly

NightPhoenix828 NightPhoenix828

2019/6/15

#
Hi, I'm trying to make the background of my game switch smoothly between two backgrounds so that the road looks like it's moving. This is what I've got at the moment:
public void imageSet()
   {
   String sRoad1 = "Road 1.png";
   String sRoad2 = "Road 2.png";
    
    setBackground(sRoad2);
    
    delayImg++;
    if (delayImg < 10) 
    {
        return;
    }
    delayImg = 0;
    
    setBackground(sRoad1);
    
    delayImg++;
    if (delayImg < 10) 
    {
        return;
    }
    delayImg = 0;
}

/**
     * Delay code:
     * https://www.greenfoot.org/topics/57766/0
     * By Super_Hippo
     * 
     * private int delay = 0;
     * delay++;
        if (delay < 4) return;
        delay = 0;
     */
This is a function I'm using in my world. For some reason, it won't switch between worlds for the same amount of time; "Road 1" flashes, and "Road 2" stays there for longer. Is there any way to make them both remain for the same amount of time?
Super_Hippo Super_Hippo

2019/6/16

#
Well, at the start of the method, you set the background to the second image. You only set it to the first image every 9 times this method is executed. I think you don't understand what the delay code is doing. Anyway, this should do it I guess.
private int delayAmount=10, delayImg=delayAmount, currentImage=0;
private GreenfootImage[] images =
{
    new GreenfootImage("Road 1.png"),
    new GreenfootImage("Road 2.png")
};

public void imageSet()
{
    if (--delayImg == 0)
    {
        delayImg=delayAmount;
        setBackground(images[(++currentImage)%images.length]);
    }
}
The delay code was quite old and I am used to do it a little bit different now (decreasing until it hits 0 instead of increasing it until it hit a certain number). Doesn't really matter in the end.
NightPhoenix828 NightPhoenix828

2019/6/16

#
Thanks! Now that I look at your code, I have no idea what I was trying to do. Let's just say it's been a long week. XD
You need to login to post a reply.