Player health bar (SOLVED)

I’m trying to build a small health bar that follows the player around.

image

I have a player collection, with the frame/border of the healthbar (stationary) and the healthbar itself:

image

I have a function:

local function take_damage(self, damage)
	self.health = math.max(0, self.health - damage)

	local sprite_pos = go.get_position("healthBar")
	local sprite_x = (self.health / self.max_health * 30) - 30

	--print(sprite_x, self.health, self.max_health, (self.health / self.max_health * 60))
	
	go.set_position(vmath.vector3(sprite_x, sprite_pos.y, sprite_pos.z), "healthBar")
	--go.set_scale(vmath.vector3(self.health / self.max_health, 1.0, 1.0), "healthBar")
end

This will make the healthBar shift to the left.

Obviously I don’t want the extra part of the healthbar image that is hanging outside the frame.

Is there a way to mask this?

Or is there a way to accomplish this with scaling or cropping the sprite?

Or any other better way to build a healthbar like this?

Thanks! :slight_smile:

1 Like

Hey!

Instead of changing the position, when decreasing health, you can scale the bar on x axis, but you will see it will be stretched not so nicely (and you will need to also move the bar a little bit, because you would probably like to have an effect of it shrinking to the left instead of to the center)

I would suggest moving the health bar to gui - it has a clipping builtin, so you could then only move it and have a desired effect.

Then you can make the GUI follow the game object and v’oila :wink:

Gui follows go example: publicexamples/examples/gui_follows_go at master · britzl/publicexamples · GitHub

GUI clipping manual: GUI clipping manual

Also GUI Progress bars example might be helpful: GUI progress indicators

4 Likes

Thank you @Pawel this is exactly what I was looking for! I actually had wanted to use a GUI.

1 Like

Glad I could help! :wink:

1 Like