using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LabelShowWithPos : MonoBehaviour
{
public Camera viewCamera;
public GameObject PosObj;
public Vector3 posVector;
public bool isWork = false;
// Start is called before the first frame update
void Start()
{
// transform.GetChild(0).gameObject.SetActive(true);
}
Vector3 screenPos;
Vector2 UIloaclPos;
// Update is called once per frame
void LateUpdate()
{
if (isWork)
{
//朝向问题,相机看不到时不显示标签
if (Vector3.Dot(posVector - viewCamera.transform.position, viewCamera.transform.forward) < 0)
{
SetState(false);
return;
}
else
{
SetState(true);
}
//世界坐标转换为对应相机的屏幕坐标
screenPos = viewCamera.WorldToScreenPoint(posVector);
//UI所在画布,若画布指定了渲染相机,则第三个参数需要改成指定相机。没有则为null
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent.GetComponent<RectTransform>(), screenPos, null, out UIloaclPos);
transform.GetComponent<RectTransform>().anchoredPosition = UIloaclPos;
}
}
public void NeedWork(bool YorN)
{
isWork = YorN;
SetState(YorN);
}
public void Init(GameObject targetObj)
{
PosObj = targetObj;
posVector = PosObj.transform.position;
}
public void Init(Vector3 targetObjPos)
{
posVector = targetObjPos;
//PosObj = new GameObject();
//PosObj.transform.localPosition = targetObjPos;
}
private void SetState(bool state)
{
transform.GetChild(0).gameObject.SetActive(state);
}
private void OnDestroy()
{
if (PosObj != null)
Destroy(PosObj);
}
}
UI效果——标签在世界位置,且朝向相机
最新推荐文章于 2023-02-03 21:57:52 发布