using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIFollowGameObj : MonoBehaviour { public GameObject TargetObj; public Camera _camera; public Vector3 Offset; private Canvas canvas; // Use this for initialization void Start () { canvas = GameObject.Find("Canvas").GetComponent(); _camera = canvas.GetComponentInChildren(); } // Update is called once per frame void Update () { //目标世界坐标转画布坐标 Vector3 worldToScreenPoint = Camera.main.WorldToScreenPoint(TargetObj.transform.position); //在画布上对应的点 worldToScreenPoint = new Vector3(worldToScreenPoint.x, worldToScreenPoint.y, canvas.planeDistance); Vector3 screenToWorldPoint = _camera.ScreenToWorldPoint(worldToScreenPoint); //得到最终画布坐标系中的投影点 Vector3 projPoint = canvas.transform.worldToLocalMatrix.MultiplyPoint(screenToWorldPoint); this.transform.localPosition = new Vector3 (projPoint.x,projPoint.y,0)+Offset; } }