做ui跟随的心得

xiaoxiao2021-02-27  454

1、经测试发现UI的rectTransform坐标信息是以像素为单位,和ScreenPoint的单位是一致的,而ScreenPoint是以左下角为原点的二维坐标轴计算的,所以只要把UI的锚点设置为左下角,那么UI的rectTransform坐标位置就是ScreenPoint的位置。

ScreenPoint直接用unity的api:Camera.main.WorldToScreenPoint(worldPos)得到。

2、用以下办法能得到ui的世界坐标

private Transform target;     private RectTransform rectTransform;     private void Awake() {         rectTransform = GetComponent<RectTransform>();     }     private void Update() {         if (rectTransform == null || target == null)              return;                  // 得到屏幕坐标         Vector2 screenPos = Camera.main.WorldToScreenPoint(target.position);         // 通过自身的rectTransform、屏幕坐标、和ui摄像机获得世界坐标         Vector3 worldPos;         if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform,screenPos,UI_Camera.Instance.Camera,out worldPos)) {             transform.position = worldPos;         }     }

转载请注明原文地址: https://www.6miu.com/read-863.html

最新回复(0)