Files
ClickRPG/Assets/Scripts/ClickController.cs
2025-10-06 15:32:09 +01:00

85 lines
2.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
public interface IInteractable
{
string GetInteractPrompt();
void OnInteract();
}
public class ClickController : MonoBehaviour
{
[SerializeField] private LayerMask layerMask;
[SerializeField] private TextMeshProUGUI promptText;
void Update ()
{
Hover();
if (Mouse.current.rightButton.wasPressedThisFrame)
Click();
}
void Click ()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray ray = Camera.main.ScreenPointToRay(mousePos);
RaycastHit hit;
// Shoot a raycast from our mouse to what ever we are pointing at.
if (Physics.Raycast(ray, out hit, 1000, layerMask))
{
// This single block now handles NPCs, ItemObjects, and more!
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
interactable.OnInteract();
}
else if (hit.collider.TryGetComponent(out Enemy enemy))
{
// Combat targeting is a different action, so it's fine to keep it separate.
Debug.Log("Enemy Clicked");
Player.Current.SetTarget(enemy);
}
else if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
Debug.Log("Ground Clicked");
Player.Current.SetTarget(null);
Player.Current.Controller.MoveToPosition(hit.point);
}
}
}
void Hover ()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray ray = Camera.main.ScreenPointToRay(mousePos);
RaycastHit hit;
// Shoot a raycast from our mouse to what ever we are pointing at.
if (Physics.Raycast(ray, out hit, 1000, layerMask))
{
//int hitLayer = hit.collider.gameObject.layer;
//if (hitLayer == LayerMask.NameToLayer("Interactable"))
if(hit.collider.TryGetComponent(out IInteractable interactable))
{
// Set the position of the prompt to the mouse position
promptText.rectTransform.position = mousePos + new Vector2(15, -15);
promptText.gameObject.SetActive(true);
promptText.text = interactable.GetInteractPrompt();
if (hit.collider.TryGetComponent(out Character character))
{
HealthBarUI.instance.UpdateInfoPanel(character.charName, character.level, character.attitude);
}
else
{
//Debug.Log("Something Else Hovered");
}
}
else
{
//Debug.Log("Something Else Hovered");
}
}
}
}