Unity3D
// 世界坐标转成UI坐标
// UI以UICamera 的形式存在
public bool WorldToUI(Vector3 world, GameObject parent, out Vector3 pos)
{Vector3 in_main_vp = MainCamera.WorldToViewportPoint(world);
if (in_main_vp.z < 0)
{
pos = Vector3.zero;
return false;
}
in_main_vp.x -= 0.5f;
in_main_vp.y -= 0.5f;
Vector3 in_screen = new Vector3(UICamera.pixelWidth * in_main_vp.x, UICamera.pixelHeight * in_main_vp.y, 0);
pos = in_screen;
CanvasScaler cs = RootUI.GetComponent<CanvasScaler>();
pos.x /= (Screen.width / cs.referenceResolution.x);
pos.y /= (Screen.height / cs.referenceResolution.y);
return true;
}
// 最后赋值
transform.localPosition = new Vector3(pt_in_ui.x, pt_in_ui.y, 0);