Files
2025TapTapGameJam/Assets/Script/Gameplay/Player/PlayerInteractorController.cs

103 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using Interface;
using System;
using Script.Gameplay.Input;
namespace Gameplay.Player
{
public class PlayerInteractorController : MonoBehaviour
{
[SerializeField] private float interactRange = 15f;
[SerializeField] private LayerMask interactableLayer;
[SerializeField] private Camera playerCamera;
[SerializeField] private bool isDrawGizmos;
[SerializeField] private bool isEnablePlayerInteraction = true; // 是否启用玩家交互功能
private IInteractable currentTarget; // 被射线命中的当前可交互对象(用于按键交互)
private IInteractable previousGazedTarget; // 上一次注视的对象(用于注视进入/离开事件)
void Start()
{
if (playerCamera == null)
playerCamera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
var input = InputManager.Instance.Input;
input.Player.Interact.performed += ctx =>
{
if (currentTarget != null)
{
currentTarget.Interact(this.gameObject);
}
};
}
void Update()
{
DetectInteractable();
}
void DetectInteractable()
{
if (playerCamera == null) return;
if (!isEnablePlayerInteraction) return;
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, interactRange, interactableLayer))
{
IInteractable hitInteractable = hit.collider.GetComponent<IInteractable>();
// 如果命中对象与之前注视的不一样,触发进入/离开事件
if (hitInteractable != previousGazedTarget)
{
if (previousGazedTarget != null)
{
previousGazedTarget.OnGazeExit(this.gameObject);
}
if (hitInteractable != null)
{
hitInteractable.OnGazeEnter(this.gameObject);
// 这里可以显示交互提示UI例如 “E - 开门”
Debug.Log(hitInteractable.GetInteractPrompt());
}
previousGazedTarget = hitInteractable;
}
currentTarget = hitInteractable;
}
else
{
// 没有命中时,如果之前有注视对象,触发离开
if (previousGazedTarget != null)
{
previousGazedTarget.OnGazeExit(this.gameObject);
previousGazedTarget = null;
}
currentTarget = null;
}
}
public void SetPlayerInteractionEnabled(bool isEnabled)
{
isEnablePlayerInteraction = isEnabled;
if (!isEnabled && previousGazedTarget != null)
{
previousGazedTarget.OnGazeExit(this.gameObject);
previousGazedTarget = null;
currentTarget = null;
}
}
void OnDrawGizmos()
{
if (isDrawGizmos) return;
if (playerCamera == null) return;
Gizmos.color = Color.green;
Vector3 origin = playerCamera.transform.position;
Vector3 direction = playerCamera.transform.forward * interactRange;
Gizmos.DrawLine(origin, origin + direction);
}
}
}