Garry's Mod trying to make a ring like health bar with seperators smooth

301 views Asked by At

So I have a ring looking like health bar in GMod, and I'm trying to make the health bar go down smoothly as I lose health, and obviously I got no idea how to do that, I've tried math approach and lerping but it didn't work (probably my poor coding was at fault) so your suggestions with those methods are still welcome

This is the function that draws my health

local function healthBar()
    local hp = ply:Health()
    local maxHp = ply:GetMaxHealth()

    surface.SetDrawColor(225,225,225,255)
    for i = 0, 180, 45 do
        function HpAng(i, maxAng)
            local curSeg = (i / maxAng) + 1
            local segAng =  (maxHp / 5)
            local segMax = segAng * curSeg
            if segMax <= hp then
                return i + maxAng
            end
            return (i + maxAng) * (hp/segMax)
        end
        draw.JRing(ScrW() / 2 + 750, ScrH() / 2 + 260, 75, 8, i + 2, HpAng(i, 45))
    end
end 

This is how the health bar looks like:

https://i.stack.imgur.com/TsKzm.jpg

1

There are 1 answers

0
92carmnad On

math.Approach moves one value towards another value by a given increment, and so the idea is that you want to increment the health currently displayed towards whatever the player's current health is, in each frame. Assuming your healthBar() function is run inside a rendering function such as HUDPaint, this should work:

local lerpHp = 0
local lerpSpeed = 0.1

local function healthBar()
    local hp = ply:Health()
    local maxHp = ply:GetMaxHealth()
    
    if (lerpHp != hp) then
        lerpHp = math.Approach(lerpHp, hp, math.abs(hp - lerpHp) * lerpSpeed)
    end
    
    surface.SetDrawColor(225,225,225,255)
    for i = 0, 180, 45 do
        function HpAng(i, maxAng)
            local curSeg = (i / maxAng) + 1
            local segAng =  (maxHp / 5)
            local segMax = segAng * curSeg
            if segMax <= lerpHp then
                return i + maxAng
            end
            return (i + maxAng) * (lerpHp/segMax)
        end
        draw.JRing(ScrW() / 2 + 750, ScrH() / 2 + 260, 75, 8, i + 2, HpAng(i, 45))
    end
end

The lerpHp variable is outside the function, since we need to keep track of what the old health was between frames.

math.abs(hp - lerpHp) increases the speed of the animation proportional to the difference in health, meaning the health bar will move faster if you have lost a larger amount of health. This is optional but this is the behaviour you'll see in most Garry's Mod HUDs.