I have the system figured out for damaging, but not for healing, but I’d be able to figure it out. But I wanted to add half hearts to this, which will complicate things much further. A half heart will only show if the player’s health’s second digit is 4, 5, or 6. But I don’t want a huge if statement that takes up 200 lines either. If a 200 line if statement is how to do it, then I’ll do it, but I want to see a more efficient solution.
So if I understand correctly, you want a system which looks like minecrafts health system? So the half heart should be at X4, X5 and X6? Or just one of them?
Either way, you can figure out what that digit is by either converting it to a string:
local health = tostring(hp)
local halfheart = hp[-1] == "<digit>" -- If it ends on that digit, then it should be half a heart
Or by doing some math. For example you can do:
local exponent = health % 10 -- Get amount of 10's fitting in health
local healthDigit = health / math.pow(10, exponent)
local halfHeart = healthDigit == <digit>
Note: Top solution only works if it is whole numbers, decimal numbers would screw it up.
I’m using health as the value of your player’s health.
Basically divide the health by 10, then subtract the rounded value of health/10.
So if health was 205 your values would be 20.5 and 20.
20.5-20 = .5
if health > 0 then
healthnew = (health/10) - (math.round(health/10))
if healthnew = .4 or healthnew = .5 or healthnew = .6 then
-- code to add 1/2 heart
end
end
if Health <= 100 and Health >= 90 then
HeartBar = 10
elseif Health <= 89 and Health >= 70 then
HeartBar = 9
--etc
end
Just an example. Assuming you want a heart system like Minecraft.
You can make this a lot more efficient.
HeartBar = math.floor((Health / 10) + .5)
-- 99 / 10 => 9.9 + .5 => 10.4 => 10
local Hearts = math.round(Humanoid.Health / 5) / 2
and here’s an equation which works for any values for health, max health and max half hearts.
local function ConvertHealthToHalfHearts(Humanoid, MaxHalfHearts) --Hearts can be empty, half or full.
return math.round(2 * (Humanoid.Health / (Humanoid.MaxHealth / (MaxHalfHearts)))) / 2
end
local Hearts = ConvertHealthToHalfHearts({Health = 350, MaxHealth = 500}, 20)
print(Hearts) --14 (7 full hearts).
The function’s first parameter expects a humanoid instance, I’ve represented one thorugh a table value to demonstrate its use.
I keep forgetting there is a .round()
and not only a .floor()
, thank you for reminding me. I believe it is possible to simplify it farther though, would this not be the same as:
local Hearts = math.round(Humanoid.Health / 10)
Since (a/b)/c = a/(b*c)
Not if you want to be able to represent half hearts.
math.round(95 / 10) --10
math.round(95 / 5) / 2 --19 / 2 = 9.5