using UnityEngine;
public class VirtualAudioListener : MonoBehaviour
{
public Camera targetCamera;
[Tooltip("耳朵离地面的固定高度")]
public float fixedHeight = 2.0f;
[Tooltip("是否修正旋转(防止因相机旋转导致左右声道错乱)")]
public bool fixRotation = true;
void LateUpdate()
{
if (targetCamera == null) return;
// 1. 计算相机视线与地面的交点 (假设地面在 Y=0)
// 简单的做法是直接取相机的 x,z,但如果相机有倾角,取视点中心更准
Vector3 cameraPos = targetCamera.transform.position;
// 简单的方案:直接取相机正下方的点
Vector3 targetPos = new Vector3(cameraPos.x, fixedHeight, cameraPos.z);
// 进阶方案:Raycast 找屏幕中心对应的地面点 (适合 RTS)
/*
Ray ray = targetCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (Physics.Raycast(ray, out RaycastHit hit, 100f, LayerMask.GetMask("Ground"))) {
targetPos = hit.point + Vector3.up * fixedHeight;
}
*/
transform.position = targetPos;
// 2. 修正旋转
if (fixRotation)
{
// 保持耳朵永远朝向世界的前方,这样屏幕的左边永远是左声道
transform.rotation = Quaternion.identity;
}
else
{
// 如果你想让耳朵跟随相机旋转(比如赛车游戏),则同步旋转
transform.rotation = targetCamera.transform.rotation;
}
}
}