User Tools

Site Tools



Ok this is not really a orx specific tutorial. It could easily used in any other environment. So what is it about, anyway? Ok so you have some object in your game, to which you want to assign a color according to some percentage. So let's say you have a health bar, that should be green, when it's full and red when it's almost empty. The following code will do this. It will scale the given percentage gradually to a color ranging from red (0 percent) over yellow(50 percent) to green(100 percent).

Implementation using RGB values

In the following percentage is a floating point number ranging from 0.0 to 1.0 and col is the resulting color. Just assign the color to any given project using orxObject_SetColor.

  orxDOUBLE percentage;
  orxCOLOR col;
  //do you want transparency?
  col.vRGB.fR=(percentage<0.5 ) ? 1.0 : 1.0 - (percentage-0.5)*1.4;
  col.vRGB.fG=(percentage>=0.5 ) ? 1.0 : (percentage*1.4)+0.3;
  //lower the saturation:
  //lower the brightness:
  orxObject_SetColor(objectref, &col);

Implementation using HSV values

An object's color has to be set using RGB values. However you have the option to use the HSV colorspace first and then convert the color object to RGB. Why would someone do that? because it is way more convenient! If you don't know what the HSV colorspace is, I recommend reading the wikipedia article about it. Instead of specifing three different colors, you specify the hue(meaning the color), the saturation and the value(brightness). So in order to scale the color of an object from red over yellow to green we just have to continuously change the hue of the object, leaving the saturation and value untouched. Just remember to convert the color object to the RGB colorspace once you're done. The code would look something like this:

  orxDOUBLE percentage;
  orxCOLOR col;
  orxCOLOR colRGB;
  //do you want transparency?
  col.vHSV.fH=0.36*percentage;//scaling it from 0(red) to 0.36(green)
  orxColor_FromHSVToRGB(&colRGB, &col);
  orxObject_SetColor(objectref, &colRGB);

  • The hue ranges from 0 to 1. Most of the time the hue will be represented in degress ranging from 0 to 360(e.g. Gimp does so). Just remember to devide the degrees by 360 and you're good.
  • The saturation ranges from 0 to 1, the latter meaning the color is fully saturated
  • The value(also brightness) also ranges from 0 to 1, the latter being the brightest
tutorials/community/tdomhan/percentage2color.txt · Last modified: 2017/05/30 05:50 (8 weeks ago) (external edit)