UI/HealthBar.razor

This component acts as a UI element for visualizing entity health. It displays a health bar whose width and color reflect the entity's current health and whether it is protected or invulnerable.

@using Sandbox;
@using Sandbox.UI;
@inherits PanelComponent
@namespace Sandbox

<root class="@(IsWorldPanel ? "full" : "") @(IsProtected ? "protected" : "")">
	<div class="fill @(Health is { IsRegening: true } ? "" : "ease-transition")" style="width: @HealthPercent%; background: @FillColor;"></div>
	@if ( IsProtected )
	{
		<div class="protection-label">PROTECTED @ProtectionSeconds s</div>
	}
</root>

@code
{
	private HealthComponent Health { get; set; }

	private float HealthPercent => !Health.IsValid() || Health.MaxHealth <= 0 ? 0 : (Health.CurrentHealth / Health.MaxHealth) * 100f;
	private bool IsProtected => Health.IsValid() && Health.IsInvulnerable;
	private int ProtectionSeconds => IsProtected ? (int)System.MathF.Ceiling( Health.SpawnProtectionRemaining ) : 0;
	private string FillColor => IsProtected ? "#168ca8" : $"hsl({Hue},85%,45%)";

	private float Hue => (@HealthPercent / 100) * 100;

	[Property] bool IsWorldPanel { get; set; }

	/// <summary>
	/// the hash determines if the system should be rebuilt. If it changes, it will be rebuilt
	/// </summary>
	protected override int BuildHash() => System.HashCode.Combine( Health?.CurrentHealth, Health?.MaxHealth, Health?.IsRegening, IsWorldPanel, IsProtected, ProtectionSeconds );

	protected override void OnStart()
	{
		Health = GetComponentInParent<HealthComponent>();
	}
}