0

I ve got class Background:

public class Background extends Sprite {
    private Color color;
    private int COLOR_SIZE = 255;



    @Override
    void update(GameCanvas canvas, float deltaTime) {
        for (int i = 0; i < COLOR_SIZE ; i++) {
            color = new Color(
                    (int)(Math.random() * i),
                    (int)(Math.random() * i),
                    (int)(Math.random() * i)
            );
        }
    }

    @Override
    void render (GameCanvas canvas, Graphics g){
        g.setColor(color);
        g.fillRect(canvas.getX(), canvas.getY(), canvas.getWidth(), canvas.getHeight());
    }

}

I need for my background to dynamically change color. I figured to get value from 0 to 255 and run it in for-loop. Problem is loop is run very fast. And color of background change very fast, how to slow for-loop or run from 0 to 255 but not so fast?

IMBABOT
  • 11
  • 1
  • 4
  • It does not make sense to change the colour in every update if you have 60FPS for example. You can change the colour when for example a [certain time](https://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java) has passed. – flaxel Sep 26 '20 at 14:53
  • 1
    For animation you use a [Swing Timer](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) to schedule the event. See: https://stackoverflow.com/a/33907282/131872 for a simple example. – camickr Sep 26 '20 at 14:57
  • 1
    @flaxel, don't use a `java.util.Timer`. Updates to Swing components should be done on the Event Dispatch Thread, which is why you need to use the Swing Timer. – camickr Sep 26 '20 at 15:01
  • @camickr Yes of course. I want to share [this answer](https://stackoverflow.com/a/11525936/10951752). I found also a [nice tutorial](https://examples.javacodegeeks.com/desktop-java/swing/timer-swing/java-swing-timer-example/). – flaxel Sep 26 '20 at 15:08

0 Answers0