One of the most common questions that I get from friends or people in my communication servers is, “How do you make a health bar that changes its color to represent a value?.” Anyways, I will be writing this short tutorial so I can help future people who ask, and anyone who was wondering in general.
Map Function
Some of you that use javascript and many other programming languages may have used this built-in function before, but what does it do? The map function takes two ranges and returns a number in the second range, relevant to the percentage of the first range if that makes sense. So if I was mapping 25 on a range of 0 to 50, 25 is 50% of 0 to 50, so on another range, for example, 0 to 100, the result would be 50, because 50 is 50% of the range 0 to 100.
Now, why is this useful? It is useful because we can take any range, like 0 to 1, which is used in the Color3.new
function, and apply that to a ‘Health’ range, which might be 0 to 100 or 0 to 10,000, you never know. Now you don’t have to use the map function if you have the max health that you are dealing with. I will show an example of both.
Map Example
local function map(num, il, iu, ol, ou)
return ol + (ou - ol) * ((num - il) / (iu - il))
end
So the map function takes five arguments, first being the number and the rest being that representing the two ranges, so for example map(25, 0, 100, 0, 1)
, with a result of 0.25
being the percentage.
Division Example
This example is definitely the easiest, requiring no function to do the math for you or anything. All you need to do is take the current health and divide it by the max health.
local health = path.to.value
local maxHealth = path.to.value
local percentage = health/maxHealth
Changing the Color
Okay so now that we have the percentage, we can use that change the values representing the color of your frame, text color or whatever.
So for example, if we were to change the text color of a TextLabel, it would look something like this.
local label = path.to.label
local humanoid = path.to.humanoid
local MAX_HEALTH = humanoid.MaxHealth
humanoid.HealthChanged:Connect(function(health)
local percentage = health/MAX_HEALTH -- or map function method map(health, 0, 1, 0, MAX_HEALTH)
label.TextColor3 = Color3.new(1 - percentage, percentage, 0)
end)
And there ya go, that’s pretty much it. Let me know how this works out for you guys!