• TOC
  • GigaMess
  • CodeTips
  • Stuff
  • Links
  • Contact

How to make changeable team & player colors?

Many people seem to have problems making a game where you can freely select your car's, tank's, ships's etc. colors. The problem isn't that hard actually. When you make a RGB-picture, you already have 3 channels: red, green and blue, which represent the changable colors.

Blue, green and red balls

This is my example picture. Now I want to make that red ball to be brown, green to be yellow and blue to be white. Notice that this picture also has antialiased lines.

Here is some pseudocode:

//slide(x,y) means an array slide(from color,to color)

//these three lines make channel 0 (red channel) brown
//(172 red, 108 green and 48 blue equals brown)
slide(0,0) = 172
slide(0,1) = 108
slide(0,2) = 48

//these three lines make channel 1 (green channel) yellow
//(256 red, 256 green and 0 blue)
slide(1,0) = 256
slide(1,1) = 256
slide(1,2) = 0

//try to quess what these lines do ;)
slide(2,0) = 256
slide(2,1) = 256
slide(2,2) = 256

//now lets convert red channel to brown, like we want
col(0, 0) = red * slide(0, 0) / 256
col(0, 1) = red * slide(0, 1) / 256
col(0, 2) = red * slide(0, 2) / 256

//green to yellow
col(1, 0) = green * slide(1, 0) / 256
col(1, 1) = green * slide(1, 1) / 256
col(1, 2) = green * slide(1, 2) / 256

//blue to white
col(2, 0) = blue * slide(2, 0) / 256
col(2, 1) = blue * slide(2, 1) / 256
col(2, 2) = blue * slide(2, 2) / 256

//sqrt=square root function. The following lines just take all the
//red, green and blue we now got and combine a new color.
new_red = sqrt(col(0, 0)^2 + col(1, 0)^2 + col(2, 0)^2)
new_green = sqrt(col(0, 1)^2 + col(1, 1)^2 + col(2, 1)^2)
new_blue = sqrt(col(0, 2)^2 + col(1, 2)^2 + col(2, 2)^2)

Here is the result I got:

White, yellow and brown balls looking good

And if you look closely, even the antialiased lines are still smooth, like expected. So you can make transparent windows and other transparent stuff with no problems.

if you want faster but not so accurate code, try changing the last three lines to these:

new_red = col(0, 0) + col(1, 0) + col(2, 0)
new_green = col(0, 1) + col(1, 1) + col(2, 1)
new_blue = col(0, 2)+ col(1, 2) + col(2, 2)

Faster but worse algorithm

Now the result is this. Antialiased lines (mixing two or more colors together, eg. thin line between white and yellow ball) are a bit too bright, but otherwise this is the same as with the slower algorithm using square root. But honestly, I don't know why anyone would need speed in this progress because it can be precalculated.

Note that you can make this algorithm to produce even better quality. Now you're just using a single color (eg. yellow) to represent what red is being changed to. But you can use an array that first changes to yellow and then to white in a beautiful ramp. This way you can create cool bright spots! I've done this for TOU, download it to see how it looks.

If you have anything to ask, just contact me.