Movement/MovementController.cs

85 lines
2.5 KiB
C#

using System.Collections.Generic;
using Syntriax.Modules.Movement.State;
using UnityEngine;
using UnityEngine.Events;
namespace Syntriax.Modules.Movement
{
public class MovementController : MonoBehaviour, IMovementController
{
public UnityEvent<IMovement> OnMovementDeactivated { get; protected set; } = null;
public UnityEvent<IMovement> OnMovementActivated { get; protected set; } = null;
private IMovement _activeMovement = null;
public IMovement ActiveMovement
{
get => _activeMovement;
protected set
{
if (_activeMovement == value)
return;
IMovement oldMovement = _activeMovement;
_activeMovement = value;
if (oldMovement != null)
OnMovementDeactivated.Invoke(oldMovement);
OnMovementActivated.Invoke(value);
}
}
public List<IMovement> Movements { get; protected set; } = null;
protected IToggleState toggleState = null;
protected virtual void Awake()
{
OnMovementDeactivated = new UnityEvent<IMovement>();
OnMovementActivated = new UnityEvent<IMovement>();
Movements = new List<IMovement>(32);
}
protected virtual void Start()
{
toggleState = GetComponent<IToggleState>();
RecacheMovements();
}
protected virtual void FixedUpdate()
{
if (!toggleState.Toggled)
return;
ActiveMovement.ApplyMovement();
}
public virtual void RecacheMovements()
{
foreach (IMovement movement in Movements)
movement.OnTakeOverStateChanged.RemoveListener(OnTakeOverListener);
Movements.Clear();
GetComponents<IMovement>(Movements);
UpdateActiveMovement();
foreach (IMovement movement in Movements)
movement.OnTakeOverStateChanged.AddListener(OnTakeOverListener);
}
private void OnTakeOverListener(bool arg0) => UpdateActiveMovement();
protected virtual void UpdateActiveMovement()
{
foreach (IMovement movement in Movements)
if (movement.CanTakeOver)
{
ActiveMovement = movement;
return;
}
ActiveMovement = Movements[Movements.Count - 1];
}
}
}