BITFALL/Assets/Artists/Scripts/GameMode/PlayerAutoSpawnController.cs

69 lines
1.6 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using BITFALL.Scene;
using BITKit;
using BITKit.Entities;
using UnityEngine;
namespace BITFALL.GameMode
{
public class PlayerAutoSpawnController : MonoBehaviour
{
[SerializeReference, SubclassSelector] private IEntitiesService entitiesService;
[SerializeReference, SubclassSelector] private ISpawnPointService _spawnPointService;
private void Start()
{
entitiesService.OnAdd += OnEntityAdded;
destroyCancellationToken.Register(() => { entitiesService.OnAdd -= OnEntityAdded; });
}
private void OnEntityAdded(IEntity obj)
{
if (obj.TryGetComponent<IHealth>(out var heal) is false) return;
var token = destroyCancellationToken;
if (obj is MonoBehaviour behaviour)
{
token = behaviour.destroyCancellationToken;
}
heal.OnSetAlive += async alive =>
{
if (alive) return;
var time = Data.Get<int>(BITConstant.Environment.mp_respawn_on_death);
switch (time)
{
case 0:
heal.HealthPoint = heal.MaxHealthPoint;
return;
case -1:
return;
default:
try
{
await Task.Delay(TimeSpan.FromSeconds(time), token);
}
catch (OperationCanceledException)
{
return;
}
if (!this) return;
heal.HealthPoint = heal.MaxHealthPoint;
if (obj.TryGetComponent<IEntityMovement>(out var movement))
{
Matrix4x4 pos = _spawnPointService.RequestSpawnPoint();
movement.Position = pos.GetPosition();
movement.Rotation = pos.rotation;
}
break;
}
};
}
}
}