Game Development Reference
In-Depth Information
Figure 9-27. The battery sprite's animating with the percent
The bar works nicely, changing with each drop in percent.
You are probably thinking it would be better if the color changed as the charge dropped lower and
lower. When scripting color values, Unity has a few presets from the Color class. Color.green , for
instance, will produce the fully saturated green used in the battery. Custom colors must be set with
a Color struct. The catch is that unlike the familiar [to some of us, at least] (256,256,256) format, you
must use the unit values, Color(1.0f,1.0f,1.0f) . As this is essentially a percent, it works out quite
well for changing the color in response to the percent of charge remaining.
For this added functionality, let's consider the green color good until 50%. At that point, it should
morph to yellow until 25% (remaining). And from there, down to red at 0%. Before tackling the math,
it is helpful to find out what the RGB numbers are for each of the target colors. You can do this
in any color picker that gives you an RGB read out. Saturated green is (0,255,0), or Color(0,1f,0).
Remember, most array values start at 0 rather than 1, so 256 becomes 255. Yellow is (255,255,0), or
Color(1f,1f,0). Red is (255,0,0). So the logic will be from 50% down to 25%, the R value will increase
by 0.4 each percent. At 25%, the G value will decrease by 0.4 each percent. Each color change
works over 1/4 of the 100%, so each percent adds 4 x 1% to the affected color.
Below the scaling code in the UpdateBattery function add:
1.
// if less than 50% and greater than 25%, adjust color- raise red to get yellow
if(percentRemaining <= 50 && percentRemaining > 25) {
float adj = (50- percentRemaining) * 0.04f; // adjusted for current percent
energyBar.GetComponent<SpriteRenderer>().color = new Color(0f + adj,1f,0f);
}
Because you are setting the color absolutely, you must calculate using the offset of the percentage
where the change is taking place (50- percentRemaining) . If this is confusing, just try working out
the numbers manually to assure yourself that the value is changing properly.
Search WWH ::




Custom Search