58 lines
1.7 KiB
C#
58 lines
1.7 KiB
C#
using UnityEngine;
|
||
using Share;
|
||
using System;
|
||
using Input;
|
||
|
||
namespace Gameplay.Player
|
||
{
|
||
public class PlayerInteractorController : MonoBehaviour
|
||
{
|
||
[SerializeField] private float interactRange = 15f;
|
||
[SerializeField] private LayerMask interactableLayer;
|
||
[SerializeField] private Camera playerCamera;
|
||
|
||
private IInteractable currentTarget;
|
||
|
||
void Start()
|
||
{
|
||
playerCamera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
DetectInteractable();
|
||
|
||
if (currentTarget != null && InputManager.Instance.InteractPressed)
|
||
{
|
||
currentTarget.Interact(this.gameObject);
|
||
}
|
||
}
|
||
|
||
void DetectInteractable()
|
||
{
|
||
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
|
||
if (Physics.Raycast(ray, out RaycastHit hit, interactRange, interactableLayer))
|
||
{
|
||
currentTarget = hit.collider.GetComponent<IInteractable>();
|
||
if (currentTarget != null)
|
||
{
|
||
// 这里可以显示交互提示UI,例如 “E - 开门”
|
||
Debug.Log(currentTarget.GetInteractPrompt());
|
||
}
|
||
}
|
||
else
|
||
{
|
||
currentTarget = null;
|
||
}
|
||
}
|
||
|
||
void OnDrawGizmos()
|
||
{
|
||
if (playerCamera == null) return;
|
||
Gizmos.color = Color.green;
|
||
Vector3 origin = playerCamera.transform.position;
|
||
Vector3 direction = playerCamera.transform.forward * interactRange;
|
||
Gizmos.DrawLine(origin, origin + direction);
|
||
}
|
||
}
|
||
} |