UGUI_UI子节点在Canvas的2D坐标
?
首先我們要搞清楚 transform.postion 和 rectTransform.anchoredPosition ?這兩個坐標是完全不一樣的。前面的是3D坐標,后面的是2D在Rect里的坐標,并且還是相對坐標,那么節點深了坐標就更不好換算了。
C#
1 2 3 4 5 6 7 8 9 | ????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的顯示位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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; ????????} ????} } |
? ?
總結
以上是生活随笔為你收集整理的UGUI_UI子节点在Canvas的2D坐标的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UGUI_UI的深度学习
- 下一篇: UGUI_不规则按钮的响应区域