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

77 lines
2.4 KiB
C#

using BITKit.Sensors;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Interactions;
namespace BITKit.Entities.Player
{
public class EntityInteractive : EntityPlayerComponent
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISensor sensor;
[Header(Constant.Header.InternalVariables)]
private ISelectable selected;
private IntervalUpdate cd = new(0.08f);
public override void OnUpdate(float deltaTime)
{
if (sensor.Get().TryGetAny(x=>x.TryGetComponentAny<ISelectable>(out _),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);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnInactive(selected);
}
selected = null;
}
private void Detected(ISelectable detected)
{
selected = detected;
detected.SetSelectionState(SelectionState.Hover);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnHover(selected);
}
}
public void Interactive(InputAction.CallbackContext context)
{
if (context.interaction is not PressInteraction || !context.performed || cd.AllowUpdate is false) return;
var _selected = selected;
if (_selected is not MonoBehaviour monoBehaviour) return;
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnActive(_selected);
}
}
}
}