Add utils + refacto

This commit is contained in:
2026-01-30 17:39:26 +01:00
parent 9ff17b5305
commit 23d3cb5d2c
29 changed files with 675 additions and 461 deletions
@@ -1,15 +1,12 @@
using UnityEngine;
using Unheimlich.Core;
using Unheimlich.Managers;
using Unheimlich.Utility;
namespace Unheimlich.Interactions.Core
{
/// <summary>
/// Detects interactable objects in front of the player camera using raycasts.
/// Triggers interaction when player presses interact button while looking at an interactable.
/// </summary>
public class InteractionHandler : MonoBehaviour
{
public static InteractionHandler Instance { get; private set; }
public class InteractionHandler : Singleton<InteractionHandler>
{
[Header("Settings")]
[SerializeField] private float _interactionRange = 1f;
@@ -19,50 +16,32 @@ namespace Unheimlich.Interactions.Core
private InteractableBase _currentInteractable;
private Camera _playerCamera;
private float _raycastTimer;
private static readonly Vector3 ViewportCenter = new Vector3(0.5f, 0.5f, 0f);
private void Awake()
protected override void OnAwake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
return;
}
Instance = this;
_playerCamera = GetComponent<Camera>();
}
private void Update()
{
_raycastTimer += Time.deltaTime;
if (_raycastTimer >= _raycastInterval)
if (RaycastHelper.ThrottledRaycastComponent(
ref _raycastTimer,
_raycastInterval,
_playerCamera,
_interactionRange,
_interactableLayers,
out InteractableBase interactable))
{
CheckForInteractable();
_raycastTimer = 0f;
_currentInteractable = interactable;
}
else if (_raycastTimer == 0f)
{
_currentInteractable = null;
}
HandleInteractionInput();
}
/// <summary>
/// Performs raycast from camera center to detect interactable objects within range.
/// Updates the current interactable reference for input handling.
/// </summary>
private void CheckForInteractable()
{
Ray ray = _playerCamera.ViewportPointToRay(ViewportCenter);
if (Physics.Raycast(ray, out RaycastHit hit, _interactionRange, _interactableLayers))
{
InteractableBase hitInteractable = hit.collider.GetComponent<InteractableBase>();
_currentInteractable = hitInteractable;
}
else
_currentInteractable = null;
}
private void HandleInteractionInput()
{
if (PlayerInputManager.Instance != null &&
@@ -79,7 +58,8 @@ namespace Unheimlich.Interactions.Core
{
Gizmos.color = _currentInteractable != null ? Color.green : Color.red;
Ray ray = _playerCamera.ViewportPointToRay(ViewportCenter);
Vector3 viewportCenter = new Vector3(0.5f, 0.5f, 0f);
Ray ray = _playerCamera.ViewportPointToRay(viewportCenter);
Gizmos.DrawRay(ray.origin, ray.direction * _interactionRange);
}
}