unity UGUI UI跟隨


實現2dUI跟隨游戲中角色的移動(應用於玩家名稱,血條,稱號)

using UnityEngine;

public class UI_Follow : MonoBehaviour
{
    public Camera m_camera;
    public Transform m_target;
    public RectTransform m_ui;
    
    private Vector3 position_sp;

    private void Awake()
    {
        if (m_camera == null)
        {
            m_camera = Camera.main;
        }
        if (m_ui == null && transform is RectTransform)
        {
            m_ui = (RectTransform)transform;
        }
    }

    private void LateUpdate()
    {
        position_sp = m_camera.WorldToScreenPoint(m_target.position);
        Format_Position(ref position_sp);
        m_ui.localPosition = position_sp;
    }

    private void Format_Position(ref Vector3 pos)
    {
        pos.x -= Content.screen_width_half;
        pos.y -= Content.screen_height_half;
        pos.x *= Content.screen_width_ratio;
        pos.y *= Content.screen_height_ratio;
    }
}
View Code
using UnityEngine;

public class Content
{
    //當前UI分辨率
    public const float UI_Width = 1366f;
    public const float UI_Height = 768f;

    //手機屏幕大小的二分之一
    public static float screen_width_half = Screen.width / 2;
    public static float screen_height_half = Screen.height / 2;

    //手機屏幕與UI的比率
    public static float screen_width_ratio = UI_Width / Screen.width;
    public static float screen_height_ratio = UI_Height / Screen.height;
}
View Code

需要根據手機分辨率與UI進行適配

另一種解決方案:

每個3D物體身上都掛載一個Canvas,通過調整UI角度實現


免責聲明!

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



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