在 Unity 中转换屏幕坐标和世界坐标
把场景物体投影到屏幕像素,再用相机深度或地面平面确定世界坐标。
把标签放在物体上方
使用实际渲染该物体的相机。游戏视图左下角像素为 (0, 0),返回的 z 是以世界单位表示的相机空间深度。相机背后的点深度为负。在屏幕空间覆盖模式的画布中,可用投影位置放置标签。
验证一次往返转换
将脚本挂到游戏对象上,再指定相机和目标。相机位于原点、朝向 +Z 且覆盖整个 800 × 600 游戏视图时,目标 (0, 0, 10) 约投影到 (400, 300, 10)。保留返回的 z,再反算即可还原目标位置。
CoordinateExample.cs
using UnityEngine;
public class CoordinateExample : MonoBehaviour
{
public Camera view;
public Transform target;
void Start()
{
Vector3 pixel = view.WorldToScreenPoint(target.position);
Vector3 restored = view.ScreenToWorldPoint(pixel);
Debug.Log($"Screen {pixel}, world {restored}");
}
public bool TryGroundPoint(Vector2 screenPixel, out Vector3 point)
{
Ray ray = view.ScreenPointToRay(screenPixel);
Plane ground = new Plane(Vector3.up, Vector3.zero);
if (ground.Raycast(ray, out float distance))
{
point = ray.GetPoint(distance);
return true;
}
point = default;
return false;
}
}把标记放到地面
单个屏幕点对应一条射线。传入游戏视图中的指针像素位置,让射线与世界平面 y = 0 相交。射线平行于地面或交点在后方时,没有前向交点。
Camera.WorldToScreenPoint · Camera.ScreenToWorldPoint · Camera.ScreenPointToRay