世界空間中的點坐標轉換到屏幕坐標:
screenPos = RectTransformUtility.WorldToScreenPoint(cam, worldPos.transform.position);
UGUI物體的坐標轉換到屏幕坐標:
screenPos = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, uguiObj.transform.position);
屏幕坐標轉換到UGUI坐標:
Vector3 worldPoint;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTrans, camPos, canvas.worldCamera,out worldPoint))
{
transform.position = worldPoint;
}
屏幕坐標轉換到世界空間坐標(射線碰撞位置):
var ray = RectTransformUtility.ScreenPointToRay(worldCamera, screenPos);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
pos.transform.position = hitInfo.point;
}
計算鼠標點擊位置到錨點位置的偏差:
Vector3 globalMousePos;
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, Input.mousePosition,
eventData.pressEventCamera, out globalMousePos);
offset = transform.position - globalMousePos;
拖動時:
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
{
transform.position = globalMousePos + offset;
transform.rotation = m_DraggingPlane.rotation;
}