87 lines
2.9 KiB
C#
87 lines
2.9 KiB
C#
// PlayerInteractController.cs
|
||
using System.Collections;
|
||
using UnityEngine;
|
||
using UnityEngine.InputSystem;
|
||
using UnityEngine.InputSystem.Controls;
|
||
|
||
public class PlayerInteractController : MonoBehaviour
|
||
{
|
||
// public KeyControl interactionKey = Keyboard.current.fKey; // 交互按键,默认为F
|
||
public float interactionRange = 2f; // 交互检测范围
|
||
public Transform interactPoint; // 交互检测的起点(通常是玩家相机或身体中心)
|
||
|
||
private IInteractable currentInteractable; // 当前可交互的对象
|
||
|
||
void Start()
|
||
{
|
||
StartCoroutine(PeriodicDetection());
|
||
}
|
||
void Update()
|
||
{
|
||
// 每帧检测附近的交互物
|
||
// DetectInteractables();
|
||
|
||
// 如果当前有可交互物体,且玩家按下了交互键
|
||
if (currentInteractable != null && Keyboard.current.fKey.wasPressedThisFrame)
|
||
{
|
||
currentInteractable.OnInteract();
|
||
}
|
||
}
|
||
private IEnumerator PeriodicDetection()
|
||
{
|
||
while (true)
|
||
{
|
||
DetectInteractables(); // 你的检测逻辑
|
||
yield return new WaitForSeconds(0.1f); // 每0.1秒检测一次
|
||
}
|
||
}
|
||
void DetectInteractables()
|
||
{
|
||
// 使用球形检测来查找范围内的所有碰撞体
|
||
Collider[] hitColliders = Physics.OverlapSphere(interactPoint.position, interactionRange);
|
||
IInteractable closestInteractable = null;
|
||
float closestDistance = float.MaxValue;
|
||
|
||
// 遍历所有碰撞体,找到最近的 IInteractable 对象
|
||
foreach (var hitCollider in hitColliders)
|
||
{
|
||
IInteractable interactable = hitCollider.GetComponent<IInteractable>();
|
||
if (interactable != null)
|
||
{
|
||
float distance = Vector3.Distance(interactPoint.position, hitCollider.transform.position);
|
||
if (distance < closestDistance)
|
||
{
|
||
closestDistance = distance;
|
||
closestInteractable = interactable;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 如果当前交互对象发生了变化
|
||
if (closestInteractable != currentInteractable)
|
||
{
|
||
// 通知旧物体退出范围
|
||
if (currentInteractable != null)
|
||
{
|
||
currentInteractable.OnExitInteractionRange();
|
||
}
|
||
// 通知新物体进入范围
|
||
if (closestInteractable != null)
|
||
{
|
||
closestInteractable.OnEnterInteractionRange();
|
||
}
|
||
// 更新当前交互对象
|
||
currentInteractable = closestInteractable;
|
||
}
|
||
}
|
||
|
||
// 在Scene视图中绘制交互范围,便于调试
|
||
private void OnDrawGizmosSelected()
|
||
{
|
||
if (interactPoint != null)
|
||
{
|
||
Gizmos.color = Color.yellow;
|
||
Gizmos.DrawWireSphere(interactPoint.position, interactionRange);
|
||
}
|
||
}
|
||
} |