UI跟随3D对象

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using Core.UI;
using Game.UI;
using UnityEngine.UI;

public class UIFollowObj : MonoBehaviour
{
    public GameObject FallowObj = null;
    public  bool isEnableFallow = true;
    public bool AllowXFollow = true;
    public bool AllowYFollow = true;
    public Camera WorldCamera;
    public Camera UICamera;
    public RectTransform Rectangle;

    private Vector3 OffsetWorldV3 = Vector3.zero;
    public  void SetOffset(float x,float y,float z)
    {
        OffsetWorldV3.x = x;
        OffsetWorldV3.y = y;
        OffsetWorldV3.z = z;
    }

    void Update()
    {
        if (!isEnableFallow || WorldCamera == null|| UICamera == null)
            return;
        if (FallowObj != null)
        {
            Vector3 screenPos = WorldCamera.WorldToScreenPoint(FallowObj.transform.position+ OffsetWorldV3);
            Vector2 localPos;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(Rectangle, screenPos, UICamera, out localPos))
            {
                transform.localPosition = localPos;
            }
        }
    }

    protected  void OnDestroy()
    {

        FallowObj = null;
    }

    public void SetFallowObject(GameObject obj)
    {
        FallowObj = obj;
    }

    public void EnableFallow(bool bVal)
    {
        isEnableFallow = bVal;
    }

    
}

猜你喜欢

转载自blog.csdn.net/weixin_41995872/article/details/128116703