BITFALL/Assets/BITKit/Unity/Scripts/Entity/Components/Interactive/EntityInteractive.cs

104 lines
3.2 KiB
C#

using System;
using BITKit.Selection;
using BITKit.Sensors;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Interactions;
namespace BITKit.Entities.Player
{
[CustomType(typeof(ISelector))]
public class EntityInteractive : EntityPlayerComponent,ISelector
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISensor sensor;
[Header(Constant.Header.InternalVariables)]
private ISelectable selected;
private IntervalUpdate cd = new(0.08f);
[Inject]
private IHealth _health;
public override void OnStart()
{
_health.OnSetAlive += OnSetAlive;
}
private void OnSetAlive(bool obj)
{
TryDeSelected();
}
public override void OnUpdate(float deltaTime)
{
//if (sensor.Get().TryGetAny(x=>x.TryGetComponentAny<ISelectable>(out _),out var detected))
if (sensor.Get().TryGetAny(x=>x.GetComponentInParent<ISelectable>() is not null,out var detected))
{
if (detected.TryGetComponentAny<ISelectable>(out var _detected))
{
if (_detected == selected)
{
}
else
{
TryDeSelected();
Detected(_detected);
}
}
else
{
TryDeSelected();
}
}
else
{
TryDeSelected();
}
}
private void TryDeSelected()
{
if (selected is null) return;
selected.SetSelectionState(SelectionState.None);
OnInactive?.Invoke(selected);
selected = null;
}
private void Detected(ISelectable detected)
{
selected = detected;
detected.SetSelectionState(SelectionState.Hover);
OnSelected?.Invoke(selected);
}
public void Interactive(InputAction.CallbackContext context)
{
if (context.interaction is not PressInteraction || !context.performed ) return;
if (cd.AllowUpdate is false) return;
var _selected = selected;
if (_selected is not MonoBehaviour monoBehaviour) return;
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
selected.SetSelectionState(SelectionState.Active);
OnActive?.Invoke(selected);
}
public bool TryGetCurrentSelectable(out ISelectable selectable)
{
selectable = selected;
return selectable != null;
}
public event Action<ISelectable> OnNone;
public event Action<ISelectable> OnHover;
public event Action<ISelectable> OnActive;
public event Action<ISelectable> OnInactive;
public event Action<ISelectable> OnFocus;
public event Action<ISelectable> OnSelected;
public event Action<ISelectable> OnEnabled;
public event Action<ISelectable> OnChecked;
public event Action<ISelectable> OnRoot;
}
}