天天看點

unity UGUI之擷取UI子節點在Canvas的2D坐标(一)

在做unityUGUI時,經常會遇到螢幕坐标轉換為ugui坐标,前段時間項目需求滑鼠點選螢幕遙杆就在手指點選的位置,會有螢幕左邊轉化為UGUI坐标來實作,今天想大家分享一下坐标轉換,這段時間主要是對UGUI問題以及優化進行詳解。如下圖所示,UI比較複雜了子節點會很多,假設我想擷取某個子的子節點的2D坐标。

unity UGUI之擷取UI子節點在Canvas的2D坐标(一)

首先我們要搞清楚 transform.postion 和 rectTransform.anchoredPosition  這兩個坐标是完全不一樣的。前面的是3D坐标,後面的是2D在Rect裡的坐标,并且還是相對坐标,那麼節點深了坐标就更不好換算了。

public Canvas canvas;
void Start()
{
	Vector2 pos;
	if(RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, transform.position, canvas.camera, out pos))
    {
		Debug.Log(pos);
	}
 
}
           

是以上述代碼就是用UI元素的世界坐标和canvas的RectTrasform再加上UI錄影機,換算出元素在Canvas的2D坐标

最後在想需要指派的UI 用 rectTransform.anchoredPosition = pos 就可以了。。

今天有朋友問我,怎麼通過滑鼠的坐标在螢幕上移動來更新UI的顯示位置。代碼如下

using UnityEngine;
using System.Collections;
 
public class NewBehaviourScript : MonoBehaviour {
 
    Canvas canvas;
    RectTransform rectTransform;
	// Use this for initialization
	void Start () 
    { 
        rectTransform = transform as RectTransform;
        canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
	}
	
	// Update is called once per frame
	void Update () {
        Vector2 pos;
        if(RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out pos)){
            rectTransform.anchoredPosition = pos;
        }
	}
}
           

實作項目的最重要的邏輯如下:

if (Input.GetMouseButton(0))
        {
            Vector2 uguiPos;
            pressing = true;
            pos = Input.mousePosition ;
            RectTransformUtility.ScreenPointToLocalPointInRectangle
            (GameEntry.GameSceneManager.uiCanvasRectTransform, pos,
            GameEntry.GameSceneManager.uiCamera, out uguiPos);
            pos = uguiPos;
            //pos = Vector3.Scale( uiCanvas.worldCamera.ScreenToViewportPoint(pos), screenSize ) - screenSize * 0.5f;
            if (PlayerMainAction.moveStart != null) PlayerMainAction.moveStart();
        }