/// <summary>
/// 屏幕坐标转换成 UI 坐标
/// </summary>
/// <param name="targetParentRect"> 目标 UI 父物体的 RectTransform </param>
/// <param name="mousePos"> 鼠标位置 </param>
/// <param name="canvasCam"> 如果Canvas的渲染模式为: Screen Space - Overlay, Camera 设置为 null;
/// Screen Space-Camera or World Space, Camera 设置为 Camera.main></param>
/// <returns>UI 的局部坐标</returns>
private Vector2 ScreenToUILocalPos(RectTransform targetParentRect, Vector2 mousePos, Camera canvasCam = null)
{
//UI 的局部坐标
Vector2 uiLocalPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(targetParentRect, mousePos, canvasCam, out uiLocalPos);
return uiLocalPos;
}
使用方法:// targetRect 目标物体,也就是UI物体
targetRect.localPosition = ScreenToUILocalPos(targetRect.parent as RectTransform, Input.mousePosition);
/// <summary>
/// 屏幕坐标转换成 UI 坐标
/// </summary>
/// <param name="targetRect"> 目标 UI 物体的 RectTransform </param>
/// <param name="mousePos"> 鼠标位置 </param>
/// <param name="canvasCam"> 如果Canvas的渲染模式为: Screen Space - Overlay, Camera 设置为 null;
/// Screen Space-Camera or World Space, Camera 设置为 Camera.main></param>
/// <returns> UI 的坐标 </returns>
private Vector3 ScreenToUIWorldPos(RectTransform targetRect, Vector2 mousePos, Camera canvasCam = null)
{
//UI 的局部坐标
Vector3 worldPos;
RectTransformUtility.ScreenPointToWorldPointInRectangle(targetRect, mousePos, canvasCam, out worldPos);
return worldPos;
}
使用方法:targetRect 目标物体,也就是UI物体
targetRect.position = ScreenToUIWorldPos(targetRect, Input.mousePosition);