Unity UGUI制作HUD Text


原文:http://www.cnblogs.com/veboys/p/4353711.html

public class HUDText : MonoBehaviour
{
    public Transform target;
    public Vector3 offset;
    private RectTransform r_Transform;

    private void Awake()
    {
        r_Transform = GetComponent<RectTransform>();
    }

    void Update()
    {
        if (target != null)
        {
            Vector3 temp = target.TransformPoint(offset);
            Vector3 ScenePos = Camera.main.WorldToScreenPoint(temp);
            r_Transform.anchoredPosition3D = ScenePos;
        }
    }
}

但這里有個注意點,直接使用會出現坐標不正常顯示的情況下。

原因是 Camera.main.WorldToScreenPoint 是把坐標轉換為屏幕坐標系,但屏幕坐標系是從左下角開始算起的,所以要把你的UI元素也設置為從左下角開始計算坐標。如下圖:

備注:

  最后還是有一點問題, 就是時不時突然出現在不對的位置,解決了再更新。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM