42 lines
1.3 KiB
C#
42 lines
1.3 KiB
C#
using GameCore.ECS.Interfaces;
|
|
|
|
namespace GameCore.Attributes;
|
|
|
|
/// <summary>
|
|
/// A component that stores all gameplay-relevant stats for an entity.
|
|
/// This design is adapted directly from the excellent CharacterAttributes class
|
|
/// in the 'broberry' project. It's a flexible, data-driven way to manage stats.
|
|
/// </summary>
|
|
public class AttributeComponent : IComponent
|
|
{
|
|
public readonly Dictionary<Attribute, float> BaseValues = new();
|
|
public readonly Dictionary<Attribute, float> CurrentValues = new();
|
|
|
|
public event Action<Attribute, float>? OnAttributeChanged;
|
|
|
|
public void SetBaseValue(Attribute attr, float value)
|
|
{
|
|
BaseValues[attr] = value;
|
|
SetCurrentValue(attr, value);
|
|
}
|
|
|
|
public float GetValue(Attribute attr)
|
|
{
|
|
return CurrentValues.GetValueOrDefault(attr, 0f);
|
|
}
|
|
|
|
public void ModifyValue(Attribute attr, float delta)
|
|
{
|
|
var newValue = GetValue(attr) + delta;
|
|
SetCurrentValue(attr, newValue);
|
|
}
|
|
|
|
public void SetCurrentValue(Attribute attr, float value, bool force = false)
|
|
{
|
|
if (CurrentValues.TryGetValue(attr, out var oldValue) && !(System.Math.Abs(oldValue - value) > 0.001f) &&
|
|
!force) return;
|
|
|
|
CurrentValues[attr] = value;
|
|
OnAttributeChanged?.Invoke(attr, value);
|
|
}
|
|
} |