Unity UGUI场景坐标转换成UI坐标

所用到的API:

 CameraHelper.MainCamera.WorldToScreenPoint(Vector3 position)
 RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint)

第一步 把需要转换的世界坐标转换为屏幕坐标

Vector3 screenPosition = CameraHelper.MainCamera.WorldToScreenPoint(worldPosition);

第二步 把转换完成的屏幕坐标转化为某个UICanvas下的坐标

Vector2 uiPosition;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
            (RectTransform)UIHelper.WorldCanvas.transform,
            screenPosition,
            UIHelper.WorldCanvas.worldCamera,
            out uiPosition))
        {
            RectTransform.localPosition = uiPosition;
        }

解读一下第二个方法所需要的参数:

RectTransform rect:你所要转换到某个canvas的RectTransform,因为UI物体全部都会是canvas的子物体
Vector2 screenPoint:需要转换的屏幕坐标
Camera cam:对应canvas的摄像机,如果为Screen Space-overlay模式 就填null
out Vector2 localPoint:最后转换出的UI坐标

你可能感兴趣的:(Unity UGUI场景坐标转换成UI坐标)