Looping through all colours

Hello, I’ve decided to post a snippet of a small algorithm I’ve come up with for looping through the spectrum of RGBA colours. I needed this as an exercise for myself (quite new to game development) and this is how I came up with a way to get my cube to keep changing colours.

It probably isn’t the most efficient or “correct” way, but it works and it might inspire somebody.

1) Declare global variables r, g, b and initialize one of them to your preferred starting colour. Haven’t tested it for white or black, but should take a couple minutes to figure that out!

private float at r = 1, g = 0, b = 0;

2) In your simpleUpdate() method, compile the following algorithm:

``````    if(b >= 1 && r < 1){
r += 0.01;
g -= 0.01;
}
if(r >= 1 && g < 1){
g += 0.01;
b -= 0.01;
}

if(g >= 1 && b < 1){
b += 0.01;
r -= 0.01;
}
``````

Basically, if the cube is fully one colour, the program will slowly reduce that colour and increase the next colour. Changing the “0.01” values will speed up the changes.

3) Now just apply the variables to whatever you need to colour in your simpleUpdate() method!

cubeMat.setColor(“Color”, new ColorRGBA(r, g, b, 1));

Thanks for reading, good luck and I hope this helped someone out there

1 Like

Just a note: often when people want to cycle through colors visually they will do it with some variation of a hue-based color model. What you have will cycle through a subset of colors and many of them will be very similar. (Plus on quick read it looks like it’s quite likely color values will go negative… which while not an ‘error’ will make the periods of similar color extra long as those negative blue values come up to 0 and above again.)

Anyway, it seems like something very specific to your use-case but you might want to check out converting to/from HSV color and then cycling just through hue… and maybe saturation.

Interesting. Thank you