// PlayerInteraction.cs - Handles player's interactions with objects using UnityEngine; using UnityEngine.UI; using TMPro; using UnityEngine.TextCore.Text; public class PlayerInteraction : MonoBehaviour { [SerializeField] private float checkRadius = 3f; [SerializeField] private LayerMask interactableMask; [SerializeField] public KeyCode interactKey = KeyCode.E; // UI references [SerializeField] private GameObject interactionPromptUI; [SerializeField] private TextMeshProUGUI promptText; [SerializeField] private float promptHeightOffset = 1.5f; // Height above the interactable private Interactable currentInteractable; private void Update() { // Check for interactable objects //CheckForInteractable(); // Handle interaction input if (Input.GetKeyDown(interactKey) && currentInteractable != null && !GameManager.GameIsPaused) { currentInteractable.Interact(); } } private void LateUpdate() { if (currentInteractable != null && interactionPromptUI.activeSelf) { // Update position every frame when active Vector3 targetPosition = currentInteractable.transform.position; // + Vector3.up * promptHeightOffset; interactionPromptUI.transform.position = targetPosition; } } public void SetCurrentInteractable(Interactable interactable) { currentInteractable = interactable; UpdateInteractionUI(); } private void CheckForInteractable() { // Cast a sphere to detect interactable objects Collider[] colliders = Physics.OverlapSphere(transform.position, checkRadius, interactableMask); Debug.Log("Checking for interactables within radius: " + checkRadius); // Find closest interactable float closestDistance = checkRadius; Interactable closestInteractable = null; Debug.Log("Found " + colliders.Length + " colliders in range."); foreach (var collider in colliders) { Debug.Log("Collider detected: " + collider.gameObject.name); if (collider.TryGetComponent(out Interactable interactable)) { float distance = Vector3.Distance(transform.position, interactable.transform.position); if (distance < closestDistance && interactable.IsInRange(transform)) { closestDistance = distance; closestInteractable = interactable; } } } // Update current interactable if (closestInteractable != currentInteractable) { currentInteractable = closestInteractable; UpdateInteractionUI(); } } private void UpdateInteractionUI() { if (currentInteractable != null) { // Update prompt text promptText.text = currentInteractable.GetPromptMessage(); // Show the prompt interactionPromptUI.SetActive(true); // Position the prompt above the interactable Vector3 targetPosition = currentInteractable.transform.position + Vector3.up * promptHeightOffset; interactionPromptUI.transform.position = targetPosition; } else { interactionPromptUI.SetActive(false); } } }