This commit is contained in:
CortexCore
2025-03-09 13:38:32 +08:00
parent 787ae12bf8
commit 88f1ff1b04
14 changed files with 181 additions and 35 deletions

View File

@@ -2,11 +2,25 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BITKit;
using BITKit.Entities;
using BITKit.WorldNode;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Net.Project.B.Health
{
public interface IHealthComponent
{
public int MaxHealthPoint { get; }
}
[Serializable]
public class HealthComponent:IHealthComponent,IWorldNode
{
public int maxHealthPoint = 100;
public int MaxHealthPoint => maxHealthPoint;
}
/// <summary>
/// 生命值服务
/// </summary>
@@ -36,13 +50,31 @@ namespace Net.Project.B.Health
/// <returns></returns>
public UniTask<int> AddHealth(int id,int value,object arg);
}
public class HealthService:IHealthService
{
private static HealthService _singleton;
public HealthService()
public class HealthService:IHealthService,IDisposable
{ private static HealthService _singleton;
private readonly IEntitiesService _entitiesService;
private static readonly ConcurrentDictionary<int, IHealthComponent> HealthComponents = new();
public HealthService(IEntitiesService entitiesService)
{
_entitiesService = entitiesService;
_singleton = this;
_entitiesService.OnAdd += OnAdd;
}
private void OnAdd(IEntity obj)
{
if (obj.ServiceProvider.GetService<IHealthComponent>() is {} healthComponent)
{
if (HealthComponents.TryAdd(obj.Id, healthComponent))
{
Healths.TryAdd(obj.Id, healthComponent.MaxHealthPoint <=0 ? 100 : healthComponent.MaxHealthPoint);
}
}
}
[BITCommand]
public static void SetHealth(int id, int newHealth)
{
@@ -55,6 +87,7 @@ namespace Net.Project.B.Health
{
Healths.GetOrAdd(id,100);
_singleton.AddHealth(id, newHealth, null).Forget();
}
@@ -75,15 +108,21 @@ namespace Net.Project.B.Health
}
public UniTask<int> AddHealth(int id, int value,object arg)
{
var current = Healths.GetOrAdd(id,100);
if (Healths.TryGetValue(id,out var current) is false) return UniTask.FromResult(-1);
foreach (var func in OnHealthChange.CastAsFunc())
{
value =func.Invoke(id,current, value, arg);
}
var newHp = Math.Clamp(current + value, -1, 100);
var newHp = Math.Clamp(current + value, -1, HealthComponents[id].MaxHealthPoint);
Healths.Set(id,newHp);
OnHealthChanged?.Invoke(id,current,newHp,arg);
return UniTask.FromResult(newHp);
}
public void Dispose()
{
_entitiesService.OnAdd -= OnAdd;
}
}
}