Movement/MovementController.cs

83 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2022-11-14 13:04:09 +03:00
using Syntriax.Modules.ToggleState;
using UnityEngine;
namespace Syntriax.Modules.Movement
{
public class MovementController : MonoBehaviour, IMovementController
{
public Action<IMovement> OnMovementDeactivated { get; set; } = null;
public Action<IMovement> OnMovementActivated { get; 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()
{
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 -= OnTakeOverListener;
Movements.Clear();
GetComponents<IMovement>(Movements);
UpdateActiveMovement();
foreach (IMovement movement in Movements)
movement.OnTakeOverStateChanged += 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];
}
}
}