109 lines
3.7 KiB
C#
109 lines
3.7 KiB
C#
using UnityEngine;
|
||
using Script.Gameplay.Interface;
|
||
using System;
|
||
using Core;
|
||
using Script.Gameplay.Input;
|
||
|
||
namespace Script.Gameplay.Player
|
||
{
|
||
public class PlayerInteractorController : MonoBehaviour
|
||
{
|
||
[SerializeField] private FirstPersonRaycaster raycaster; // 新增:第一人称射线检测器
|
||
[SerializeField] private bool isEnablePlayerInteraction = true; // 是否启用玩家交互功能
|
||
|
||
private IInteractable currentTarget;
|
||
private IInteractable CurrentTarget
|
||
{
|
||
get => currentTarget;
|
||
set
|
||
{
|
||
currentTarget = value;
|
||
if (currentTarget != null)
|
||
{
|
||
// 可以在这里添加一些逻辑,比如显示交互提示UI
|
||
OnGazeEnter?.Invoke(this.gameObject);
|
||
}
|
||
else
|
||
{
|
||
// 可以在这里隐藏交互提示UI
|
||
OnGazeExit?.Invoke(this.gameObject);
|
||
}
|
||
}
|
||
} // 被射线命中的当前可交互对象(用于按键交互)
|
||
private IInteractable previousGazedTarget; // 上一次注视的对象(用于注视进入/离开事件)
|
||
|
||
public event Action<GameObject> OnGazeEnter;
|
||
public event Action<GameObject> OnGazeExit;
|
||
|
||
void Start()
|
||
{
|
||
if (raycaster == null)
|
||
raycaster = GetComponent<FirstPersonRaycaster>() ?? GetComponentInChildren<FirstPersonRaycaster>();
|
||
if (raycaster == null)
|
||
raycaster = FindObjectOfType<FirstPersonRaycaster>();
|
||
if (raycaster == null)
|
||
Debug.LogWarning("FirstPersonRaycaster not found! Please assign or add it to the player.");
|
||
|
||
var input = InputManager.Instance.Input;
|
||
input.Player.Interact.performed += ctx =>
|
||
{
|
||
if (CurrentTarget != null)
|
||
{
|
||
CurrentTarget.Interact(this.gameObject);
|
||
}
|
||
};
|
||
|
||
ControllerLocator.Instance.Register(this);
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
DetectInteractable();
|
||
}
|
||
|
||
void DetectInteractable()
|
||
{
|
||
if (raycaster == null) return;
|
||
if (!isEnablePlayerInteraction) return;
|
||
|
||
GameObject lookAtObj = raycaster.CurrentLookAtObject;
|
||
IInteractable hitInteractable = lookAtObj != null ? lookAtObj.GetComponent<IInteractable>() : null;
|
||
|
||
// 如果命中对象与之前注视的不一样,触发进入/离开事件
|
||
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;
|
||
}
|
||
|
||
public void SetPlayerInteractionEnabled(bool isEnabled)
|
||
{
|
||
isEnablePlayerInteraction = isEnabled;
|
||
if (!isEnabled && previousGazedTarget != null)
|
||
{
|
||
previousGazedTarget.OnGazeExit(this.gameObject);
|
||
previousGazedTarget = null;
|
||
CurrentTarget = null;
|
||
}
|
||
}
|
||
|
||
void OnDrawGizmos()
|
||
{
|
||
// 交由 FirstPersonRaycaster 绘制射线
|
||
}
|
||
}
|
||
} |