How to create differently colored characters?

Some games let player choose a color, and dye his units in this color.

To achieve this feature, what should I do? (I am just doing a 2-D game)

  1. Limit the colors to 8 kinds and draw 8 sets?
  2. Other ways?

This is what I’ve done with terrain, which is static and doesn’t change. There may be complicating factors with animated characters, but should work in principle:

  • Create the characters with the desired vari-colour areas drawn in grey scale.
  • Create mask bitmap the same shape as those areas. Imagine like you’re going to spray-paint them.
  • Perform the spray-paint operation “through the mask” using the appropriate combination of Porter Duff rules (e.g. see
    http://ssp.impulsetrain.com/porterduff.html) and an appropriate alpha value to set the intensity of the colour.
  • Rules: DST_IN to do the mask and SRC_ATOP to make the final combo image works.
  • Alpha: Less than 1 let the grey-scale texture show through, or 1 for just solid colour

Mate you got answer is very good.

But in the 2nd procedure, how can I make that bitmap, and save and reuse the bitmap.

Assuming that you have a pixel as a vec4, you can convert it to grayscale with this simple function.


vec4 toGrayscale (in vec4 color)
{
    float average = (color.r + color.g + color.b) / 3.0;
    return vec4(average, average, average, 1.0);
}

Now you can simply multiply it by your color to colorize it.


vec4 finalColor = grayscale * myColor;

And that does the job.

Actually what I said before was too complicated. I was only doing the DST_IN part in my code because I was creating the masks on the fly to match tile shape. For your characters you could create the mask it in Paint.NET or whatever you’re painting the originals with. Open original image, draw round the area by hand or use the magic wand tool, fill everything outside boundary with null, everything inside with white. Save as mask image.

When I’ve done this I’ve generated the mask in code to be the pixels which are pure grey (i.e. zero saturation). Any pixel which needs to be invariant grey can have a non-zero saturation (e.g. #cccccd) without anyone noticing.

Unless you are using Java2D (assume that is not the case), you can use this in shaders as I said before. Here’s a link for testing shaders online.

http://goo.gl/mxK3gH

How this works:

[tr]
[td]


fragColor = fColor;

[/td]
[td]


fragColor = toGrayscale(fColor);

[/td]
[td]


fragColor = toGrayscale(fColor) * vec4(1.0, 0.0, 0.0);

[/td]
[/tr]

^ Ah yes, my thoughts were Java2D based. If special shading APIs are available def use them.