Health Bar Class

Here is a simple health bar class that can be included as a dependency in one of your projects

--# Main
-- Health Bar

function setup()
    parameter.number("value", 0,100,100)
    h = HealthBar(10,HEIGHT/2,WIDTH-20,value,20)
end

function draw()
    background(0)
    h:draw(value)
    
end

--# HealthBar
HealthBar = class()

function HealthBar:init(x,y,w,v,s,n)
    self.x = x
    self.y = y
    self.width = w
    self.health = v
    self.max = v
    self.green = self.health / (self.max/255)
    self.red = 255- self.health / (self.max/255)
    self.strokewidth = s or 5
    self.varname=n -- a string containing the name of the variable this watches(optional)
end

function HealthBar:draw(v)
    self.health = v or loadstring("return "..self.varname)()

    self.green = self.health / (self.max/255)
    self.red = 255- self.green
    
    pushStyle()

    lineCapMode(SQUARE)
    
    stroke(self.red,self.green,0)

    strokeWidth(self.strokewidth)

    line(self.x,self.y,self.x+(self.width/self.max*self.health),self.y)
    
    popStyle()
end

Nice job @Coder! Very efficient code, and colorful, too :). I am working on a tower defense game, and I will probably use the algorithm that you have here for color change, if that is OK with you. The color change is very smooth.

@TheSolderKing Thanks. You are welcome to use it in one of your projects :smiley:

@Coder I like it, green to red for health is great, I always used a red bar all the way. I think I might use this in my game when I add in weapons and AI (which I dread to do)

@Luatee yeah. AI is scary

AWSOME! I will use this in two games I am building, Erick’s Quest and Warrior!

Thanks for the good feedback guys. Maybe I will make it into a shader sometime…

Nooooooo! slaps if you make it a shader I’ll be too confused on how to work it ;-;