Unity objects are in world coordinates, and a series of transformations are required to align objects in the UI with objects in the world.
private void ShowTowerUpgrade(TowerCtrl ctrl)
{
towerCtrl = ctrl;//3D世界里的物体
transform.localPosition = WorldPointToUILocalPoint(ctrl.transform.position);
}
private Vector3 WorldPointToUILocalPoint(Vector3 point)
{
//将世界坐标转为屏幕坐标
Vector3 screenPoint = Camera.main.WorldToScreenPoint(point);
//将屏幕坐标转换到RectTransform的局部坐标中
Vector2 uiPosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent.GetComponent<RectTransform>(), screenPoint, UIManager.Instance.UICamera, out uiPosition);
return uiPosition;
}
This code is hung on m_Upgrade in the UI, so the transform in the code refers to the transform of m_Upgrade