using System; using BITKit.PlayerCamera; 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 : EntityPlayerBehavior,ISelector { [Header(Constant.Header.Settings)] [SerializeReference, SubclassSelector] private ISensor sensor; [Header(Constant.Header.Gameobjects)] [SerializeField] private Transform sensorTransform; [Header(Constant.Header.InternalVariables)] private ISelectable selected; private IntervalUpdate cd = new(0.08f); [Inject] private IHealth _health; [Inject(true)] private IEntityMovement _movement; [Inject(true)] IPlayerCameraService _cameraService; public override void OnStart() { _health.OnSetAlive += OnSetAlive; } private void OnSetAlive(bool obj) { TryDeSelected(); } public override void OnUpdate(float deltaTime) { if (_cameraService is not null && _movement is not null) { if (_cameraService.IsCameraActivated) { sensorTransform.SetPositionAndRotation(_cameraService.CameraPosition, _cameraService.CameraRotation); } else { sensorTransform.position = _movement.Position + _movement.Rotation * _movement.ViewCenter; sensorTransform.rotation = _movement.ViewRotation; } } //if (sensor.Get().TryGetAny(x=>x.TryGetComponentAny(out _),out var detected)) try { if (sensor.Get().TryGetAny(x=>x.GetComponentInParent() is not null,out var detected)) { if (detected.TryGetComponentAny(out var _detected)) { if (_detected == selected) { } else { TryDeSelected(); Detected(_detected); } } else { TryDeSelected(); } } else { TryDeSelected(); } } catch(MissingReferenceException e) {} catch (Exception e) { Console.WriteLine(e); throw; } } 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(out var action)) { action.Execute(); } else { } selected.SetSelectionState(SelectionState.Active); OnActive?.Invoke(selected); } public bool TryGetCurrentSelectable(out ISelectable selectable) { selectable = selected; return selected?.Transform; } public event Action OnNone; public event Action OnHover; public event Action OnActive; public event Action OnInactive; public event Action OnFocus; public event Action OnSelected; public event Action OnEnabled; public event Action OnChecked; public event Action OnRoot; } }