用途:显示角色头顶UI(名称、血条等)

玩家头顶UI.gif
方法
- 屏幕坐标 = camera.WorldToScreenPoint(世界坐标)
- 角色头顶UI位置 = camera.WorldToScreenPoint(角色的世界坐标)+ 位置偏移
示例代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 设置玩家头顶UI的位置
/// </summary>
public class HeadUI : MonoBehaviour
{
public Transform targetTrans;
public Transform headUiTrans;
public Vector3 posOffset = Vector3.up * 100f;
// 将目标(即玩家角色)的世界坐标转为屏幕中的坐标
private Vector3 TargetPos { get { return cam.WorldToScreenPoint(targetTrans.position); } }
// 为了让头顶UI显示在玩家的上方,因此头顶UI的坐标是在原坐标基础上做一个向上的偏移
private Vector3 Pos { get{ return TargetPos + posOffset; } }
private Camera cam;
private void Start()
{
Init();
}
private void Init()
{
cam = Camera.main;
}
private void Update()
{
headUiTrans.position = Pos;
}
}