BITKit/Packages/Runtime~/Unity/Common/Scripts/Entity/Components/Interactive/EntityInteractive.cs

116 lines
3.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Interactions;
using BITKit;
namespace BITKit.Entities
{
public class EntityInteractive : EntityInputComponent
{
[Header(Constant.Header.Settings)]
public float distance;
public LayerMask layerMask;
[Header(Constant.Header.Input)]
public InputActionReference interactiveAction;
InputActionGroup inputActionGroup = new();
[Header(Constant.Header.InternalVariables)]
ISelectable selected;
IntervalUpdate cd = new(0.08f);
public override void OnStart()
{
base.OnStart();
}
public override void OnSpawn()
{
base.OnSpawn();
if (isLocalPlayer)
{
inputActionGroup.RegisterCallback(interactiveAction, OnInteractive);
}
}
public override void OnDespawn()
{
base.OnDespawn();
if (isLocalPlayer)
{
inputActionGroup.UnRegisterCallback(interactiveAction, OnInteractive);
}
}
public override void OnUpdate(float deltaTime)
{
if (isLocalPlayer)
{
var ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
if (Physics.Raycast(ray, out var raycastHit, distance, layerMask))
{
if (raycastHit.transform.TryGetComponentAny<ISelectable>(out var _detected))
{
if (_detected == selected)
{
}
else
{
TryDeSelected();
Detected(_detected);
}
}
else
{
TryDeSelected();
}
}
else
{
TryDeSelected();
}
}
}
void TryDeSelected()
{
if (selected is not null)
{
selected.SetSelectionState(SelectionState.None);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnInactive(selected);
}
selected = null;
}
}
void Detected(ISelectable detected)
{
selected = detected;
detected.SetSelectionState(SelectionState.Hover);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnHover(selected);
}
}
public override void OnInteractive(InputAction.CallbackContext context)
{
if (context.interaction is TapInteraction && context.performed)
{
var selected = this.selected;
if (selected is not null)
{
if (selected is MonoBehaviour monoBehaviour)
{
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnActive(selected);
}
}
}
}
}
}
}