BITFALL/Assets/BITKit/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 : EntityPlayerComponent
{
[Header(Constant.Header.Settings)]
public float distance;
public LayerMask layerMask;
[Header(Constant.Header.Input)]
public InputActionReference interactiveAction;
private readonly InputActionGroup inputActionGroup = new();
[Header(Constant.Header.InternalVariables)]
private ISelectable selected;
private IntervalUpdate cd = new(0.08f);
public override void OnStart()
{
base.OnStart();
}
public override void OnPlayerInitialized()
{
base.OnPlayerInitialized();
if (isLocalPlayer)
{
inputActionGroup.RegisterCallback(interactiveAction, OnInteractive);
}
}
public override void OnPlayerDispose()
{
base.OnPlayerDispose();
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 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);
}
}
}
}
}
}
}