上代码:
public Vector3 GetUIToWordPos(GameObject uiObj)
{
Vector3 ptScreen = RectTransformUtility.WorldToScreenPoint(Camera.main, uiObj.transform.position);
ptScreen.z = 0;
ptScreen.z = Mathf.Abs(Camera.main.transform.position.z - transform.position.z);
Vector3 ptWorld = Camera.main.ScreenToWorldPoint(ptScreen);
return ptWorld;
}
public Vector3 GetWorldToUIPos(GameObject worldObj, GameObject uiObj)
{
Vector3 originOff;
originOff = new Vector3(-Screen.width / 2, -Screen.height / 2);
Vector3 position = Camera.main.WorldToScreenPoint(worldObj.transform.position) + originOff;
position.z = 0;
RectTransform rt = uiObj.transform.GetComponent<RectTransform>();
Vector2 pivot = rt.pivot;
switch (pivot.x)
{
case 1:
position.x += rt.sizeDelta.x / 2;
break;
case 0:
position.x -= rt.sizeDelta.x / 2;
break;
}
switch (pivot.y)
{
case 1:
position.y += rt.sizeDelta.y / 2;
break;
case 0:
position.y -= rt.sizeDelta.y / 2;
break;
}
return position;
}
使用方式举例
public GameObject cube;
public GameObject image;
cube.transform.position = GetUIToWordPos(image);
image.transform.localPosition = GetWorldToUIPos(cube, image);
参考链接 Unity UGUI坐标与世界坐标转换 Unity C# 3D世界坐标转2D屏幕坐标
|