Movement/Runtime/MovementController.cs

105 lines
3.2 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
{
2022-12-01 23:30:02 +03:00
public Action<float, float, float> OnMoveCalled { get; set; } = null;
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);
}
}
2022-12-17 11:59:08 +03:00
private bool areBothToggleStatesToggled => ToggleStateMember.IsToggledNullChecked() && toggleStateOnGameObject.IsToggledNullChecked();
2022-12-01 23:30:02 +03:00
public List<IMovement> Movements { get; protected set; } = new List<IMovement>(32);
2022-12-17 11:59:08 +03:00
public IToggleState ToggleStateMember { get; protected set; } = new ToggleStateMember(true);
2022-12-01 23:30:02 +03:00
protected IToggleState toggleStateOnGameObject = null;
protected virtual void Start()
{
if (GetComponent<DefaultMovement>() == null)
gameObject.AddComponent<DefaultMovement>();
2022-11-15 16:26:26 +03:00
RecacheMovements();
2022-12-01 23:30:02 +03:00
toggleStateOnGameObject = GetComponent<IToggleState>();
toggleStateOnGameObject.OnToggleStateChanged += (_) => InvokeOnMoveAction();
2022-12-17 11:59:08 +03:00
ToggleStateMember.OnToggleStateChanged += (_) => InvokeOnMoveAction();
}
protected virtual void FixedUpdate()
{
if (!areBothToggleStatesToggled)
return;
ActiveMovement?.ApplyMovement();
}
public virtual void RecacheMovements()
{
foreach (IMovement movement in Movements)
movement.OnTakeOverStateChanged -= OnTakeOver;
Movements.Clear();
GetComponents<IMovement>(Movements);
UpdateActiveMovement();
foreach (IMovement movement in Movements)
movement.OnTakeOverStateChanged += OnTakeOver;
}
private void OnTakeOver(bool arg0) => UpdateActiveMovement();
protected virtual void UpdateActiveMovement()
{
foreach (IMovement movement in Movements)
if (movement.CanTakeOver)
{
ActiveMovement = movement;
return;
}
}
private Vector3 lastMove = Vector3.zero;
public void Move(float x = 0, float y = 0, float z = 0)
2022-12-01 23:30:02 +03:00
{
ActiveMovement?.Move(x, y, z);
(lastMove.x, lastMove.y, lastMove.z) = (x, y, z);
InvokeOnMoveAction();
}
private void InvokeOnMoveAction()
{
if (!areBothToggleStatesToggled)
return;
OnMoveCalled?.Invoke(lastMove.x, lastMove.y, lastMove.z);
2022-12-01 23:30:02 +03:00
}
}
}