方法其实啊网上很多就不多说,只说一下ScreenPointToLocalPointInRectangle关键参数的解释,网上讲得比较少
RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint)
rect:需要计算的UI节点的父节点
cam:UI相机,【重点如果UI的Canvas的模式为ScreenSpace-Overlay,则这里直接传null】
直接上代码(ScreenSpace-Overlay模式)
private void SetUIPosition(GameObject m_3dObject,RectTransform uiObject)
{
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(MainSceneObjectController.sceneCamera, m_3dObject.transform.position);
Vector2 localPoint;
//Camera uiCamera =UIManager.GetCamera("DefaultUI");
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(uiObject.parent.GetComponent<RectTransform>(), screenPoint, null, out localPoint))
{
uiObject.anchoredPosition = localPoint;
}
}