Movement/2D/MovementController.cs

62 lines
1.8 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 IMovement ActiveMovement { get; protected set; } = null;
public UnityEvent<IMovement> OnMovementChanged { get; protected set; } = new UnityEvent<IMovement>();
protected List<IMovement> movements = new List<IMovement>(32);
protected IToggleState toggleState = null;
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;
OnMovementChanged.Invoke(ActiveMovement);
return;
}
ActiveMovement = movements[movements.Count - 1];
OnMovementChanged.Invoke(ActiveMovement);
}
}
}