Skewed HP Meter

SDF-based shader to generate a skewed hp bar with adjustable max value and fill value.

One limitation is that changing the max value will stretch the meter. An improvement would be to account for this in the shader, but you can also account for it in code to adjust the Control’s height or width in your UI.

 

Stay slothy~

-Sloth Boss

Shader code
shader_type canvas_item;
uniform float thickness : hint_range (0.0, 2.0) = 0.5;
uniform float skew : hint_range(-1.0, 1.0) = 0.7;
uniform vec4 fill_color: source_color;
uniform vec4 bg_color: source_color;
uniform float max_value = 5.0;
uniform float value = 5.0;

// rotate coords
vec2 rotate(vec2 p, float angle) {
    float s = sin(angle);
    float c = cos(angle);
    return vec2(c * p.x - s * p.y, s * p.x + c * p.y);
}

// anti-aliasing
float autoAA(vec2 p) {
	return fwidth(p.x) * 1.5;   
}

// credit: iq - https://iquilezles.org/articles/distfunctions2d/
float sdParallelogram( in vec2 p, float wi, float he, float sk )
{
	vec2 e = vec2(sk, he);
	p = (p.y<0.0)?-p:p;
	vec2  w = p - e; w.x -= clamp(w.x,-wi,wi);
	vec2  d = vec2(dot(w,w), -w.y);
	float s = p.x*e.y - p.y*e.x;
	p = (s<0.0)?-p:p;
	vec2  v = p - vec2(wi,0); v -= e*clamp(dot(v,e)/dot(e,e),-1.0,1.0);
	d = min( d, vec2(dot(v,v), wi*he-abs(s)));
	return sqrt(d.x)*sign(-d.y);
}

// draw helper
float fill(float d, float aa) {
    return 1.0 - smoothstep(0.0, aa, d);
}

void fragment() {
	// repeat max_value num times
	vec2 uv = vec2(UV.x, fract(UV.y*max_value));

	// this will taper the meter
	//uv.x -= (max_value - UV.y*max_value)/max_value;
	
    vec2 p = (uv - 0.5) * 2.0;
    float aa = autoAA(p);
	// rotate to keep l/r edges instead of t/b flat
	p = rotate(p, PI/2.);

    float d = sdParallelogram(p, thickness, 1., skew);
	float fill_mask = fill(d, aa);
	vec4 c = (max_value - UV.y*max_value) >= value ? bg_color : fill_color;
	vec4 col = mix(vec4(0.0), c, fill_mask);
    COLOR = col;
}
Live Preview
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

guest

0 Comments
Oldest
Newest Most Voted