You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
1.1 KiB
30 lines
1.1 KiB
4 years ago
|
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<Canvas>();
|
||
|
_camera = canvas.GetComponentInChildren<Camera>();
|
||
|
}
|
||
|
|
||
|
// 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;
|
||
|
}
|
||
|
}
|