using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIFollow : MonoBehaviour {
public GameObject heightFollowObj; //UI跟随的3D物体
public RectTransform heightUITarget; //跟随的UI
public RectTransform uiParenttt; //移动UI的父物体,因为我的UI直接挂在Canvas下面,所以这里选的是Canvas
void Start () {
}
// Update is called once per frame
void Update () {
World2UI(heightFollowObj.transform.position, uiParenttt, heightUITarget);
}
//世界坐标转成UI中父节点的坐标, 并设置子节点的位置
public void World2UI(Vector3 wpos, RectTransform uiParent, RectTransform uiTarget)
{
Vector3 spos = Camera.main.WorldToScreenPoint(wpos); //获取屏幕坐标
Vector2 vv = new Vector2(spos.x, spos.y);
Vector2 retPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(uiParent, vv, uiParent.GetComponent<Canvas>().worldCamera, out retPos); //注意这里是UI相机
uiTarget.anchoredPosition =new Vector2( retPos.x-80, retPos.y);
}
}
FR:徐海涛(hunk Xu)
QQ技术交流群:386476712