unity屏幕坐标转世界坐标

“Orthographic”(垂直观察角度):

与canvas到摄像机的距离无关,z值无影响,直接用x,y就能算出

“Perspective”(放射观察角度):

与canvas到摄像机的距离(canvas中的planedistance)有关,z值传planedistance。

在工作中遇到一种情况:canvas有角度,这个方法就用不了了,想出一种新方法:

ScreenPointToRay会返回一条从像机到你给的点的射线,再算出canvas的法向量,再求出法向量和射线的夹角,就可以得出摄像机到你给的点的距离dis,你要的世界坐标:ray.GetPoint(dis)

代码:

Ray ray = camera.Main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0));
Vector3 ray2 = -Vector3.Cross(corners[0] - corners[2],corners[1] - corners[3]);//corners是canvas的四个角
float rad = Vector3.Angle(ray.direction,ray2);
float dis = TheaterBattleTeamSelectionUIController.Instance.canvasDistance / Mathf.Cos(rad * Mathf.Deg2Rad);
newPos = ray.GetPoint(dis);

原文地址:https://www.cnblogs.com/mcyushao/p/14928300.html