In my Java game I am making a health bar. The player's health can range from 0.0 to 100.0. I want to select a color between red and green depending on the player's health. If the health is 100.0, the color should be rgb(0, 255, 0). If the health is 0.0, the color should be rgb(255, 0, 0). Likewise, if the health = 50.0, then the color should be rgb(127, 127, 0). So the color it returns is a mixture between red and green depending on the health. How can I accomplish this?
Asked
Active
Viewed 372 times
-2
-
You may be doing your brain a disservice by not allowing it to try to write the code first itself, and you may be giving it an insult by not thinking that it is capable of doing so. I'm betting that it is. I say, give it a go first, and see what you come up with -- you may be pleasantly surprised. – Hovercraft Full Of Eels Jun 24 '15 at 01:31
-
Why the down-votes: because you've not shown any evidence of effort yet. Surely you've tried to solve this, so show us what you've got. – Hovercraft Full Of Eels Jun 24 '15 at 01:31
-
4@MCMastery You've asked for code with zero effort. This is also a simple problem for anyone familiar with basic mathematics so it would be nice to see at least your attempt at a solution. – Kon Jun 24 '15 at 01:31
-
2Take a look at [this example](http://stackoverflow.com/questions/13223065/color-fading-algorithm/13223818#13223818) and [this example](http://stackoverflow.com/questions/21270610/java-smooth-color-transition/21270957#21270957) – MadProgrammer Jun 24 '15 at 01:33
-
I sincerely hope that your future questions will show *some* evidence of effort. – Hovercraft Full Of Eels Jun 24 '15 at 01:39
2 Answers
0
Assuming you want it to vary linearly (which seems plausible):
- Red: 255 - health * 2.55
- Green: health * 2.55
- Blue: 0
This works because if you want it to vary linearly, you will have something in the form A * health + B.

Pedro A
- 3,989
- 3
- 32
- 56
0
Something simple like this?
import java.awt.Color;
public class QuickTester {
public static void main(String[] args) {
System.out.println(getColor(100).toString());
System.out.println(getColor(75).toString());
System.out.println(getColor(50).toString());
System.out.println(getColor(25).toString());
System.out.println(getColor(0).toString());
}
private static Color getColor(double currHp) {
int green = ((int) (currHp / 100.0 * 255));
int red = 255 - green;
return new Color(red, green, 0);
}
}
Output:
java.awt.Color[r=0,g=255,b=0]
java.awt.Color[r=64,g=191,b=0]
java.awt.Color[r=128,g=127,b=0]
java.awt.Color[r=192,g=63,b=0]
java.awt.Color[r=255,g=0,b=0]
You could just use the Color
returned directly, I am using toString()
for prototyping.

almightyGOSU
- 3,731
- 6
- 31
- 41
-
Perfect, thank you! I just came out of Algebra so sometimes I can't think of solutions as quickly :p – MCMastery Jun 24 '15 at 01:37