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

2026/6/23

Need Help

ThatsNotCode ThatsNotCode

2026/6/23

#
I can't figure out how to make my background change colors every ten seconds, if someone could help me that would be amazing
danpost danpost

2026/6/23

#
ThatsNotCode wrote...
I can't figure out how to make my background change colors every ten seconds, if someone could help me that would be amazing
With a simple int timer field: (note that at normal running speed, act is run about 60 times per second; hence value used)
private int bgTimer;

public void act() {
    if (bgTimer == 0) changeBgColor(); // timer check
    bgTimer = ++bgTimer%600; // timer tick
}
If using a range of colors:
Color[] bgColors = new Color[] { Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED };
int bgColorNum; // array pointer

private void changeBgColor() {
    // create color image
    GreenfootImage image = new GreenfootImage(getWidth(), getHeight());
    image.setColor(bgColors[bgColorNum]);
    bgColorNum = (bgColorNum+1)%bgColors.length;
    image.fill();
    image.setTransparency(80); // change or remove as needed
    
    // change background
    getBackground().setColor(Color.WHITE);
    getBackground().fill();
    getBackground().drawImage(image, 0, 0);
}
Note that the background image should never be set to an image with any transparency, but drawing one onto the already opaque image of the background is okay. If not using the transparency line, you can remove everything about image and just use lines 11 and 12 to change the background color and the line to adjust bgColorNum:
getBackground().setColor(bgColors[bgColorNum]);
bgColorNum = (bgColorNum+1)%bgColors.length;
getBackground().fill();
You need to login to post a reply.