方式一: 使用 RectTransformUtility.ScreenPointToLocalPointInRectangle
/// <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);
方式二: 使用 RectTransformUtility.ScreenPointToWorldPointInRectangle
/// <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);
文章来源地址https://uudwc.com/A/9vzRD
文章来源:https://uudwc.com/A/9vzRD