Vector3 UIToWorldMapDistance(UIObject ui)//UI元件的3维坐标,z表示此元件在屏幕上的位置到世界地图上的距离 { float cameraHeight = Camera.main.transform.position.y;//摄像机到世界地图的距离 Vector3 screenPos = (ui的屏幕坐标);
bool highThanCenter = screenPos.y>Screen.height*0.5f; float ratio = Mathf.Abs((screenPos.y - Screen.height * 0.5f) / (Screen.height * 0.5f));//算出ui在屏幕上的比例关系 float centerLineLength = cameraHeight / Mathf.Cos(Mathf.Deg2Rad * (90 - Camera.main.transform.eulerAngles.x)); float bottomLength = centerLineLength * Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView * 0.5f); float acturalLength = bottomLength * ratio; float requireAngle = Mathf.Atan(acturalLength / centerLineLength); float bevelLength = cameraHeight / Mathf.Cos(Mathf.Deg2Rad * (90 - Camera.main.transform.eulerAngles.x) + (highThanCenter? requireAngle:-requireAngle)); float finalLength = bevelLength * Mathf.Cos(requireAngle);//表示此元件在屏幕上的位置到世界地图上的距离
screenPos.z=finalLength;
return screenPos; }
然后用Camera.main.ScreenToWorldPoint(ui的screenPos)进行 转换即可。
原理就是根据ui在屏幕上的位置,算出比例,然后利用投影中的相似三角形原理算出准确的距离,三维的原理图比较难画,就不画了,大家可以按照这个思路自己研究一下。
上述代码中的摄像机是经过Y轴和X轴旋转的,如果摄像机的位置和旋转变化没有很多,计算应该会更加方便。