UI_Follow脚本挂载到需要跟随的3D人物上
offset为偏移量
rectTransform为需要跟随的UI
UI普通创建无需调整Canvas的Render Mode模式,无需将UI放到3D人物下面
public class UI_Follow : MonoBehaviour {
/// <summary>
/// 偏移量
/// </summary>
public Vector2 offset;
/// <summary>
/// 人物头顶标识
/// </summary>
public RectTransform rectTransform;
void Update()
{
FollowPlayer();
}
/// <summary>
/// UI跟随人物
/// </summary>
void FollowPlayer()
{
if (rectTransform == null) return;
Vector2 screenPos = Camera.main.WorldToScreenPoint(transform.position);
rectTransform.position = screenPos + new Vector2(offset.x, offset.y);
if (screenPos.x > Screen.width || screenPos.x < 0 || screenPos.y > Screen.height || screenPos.y < 0) rectTransform.gameObject.SetActive(false);
else rectTransform.gameObject.SetActive(true);
}
}
将UI创建在3D人物下方
创建一个脚本在这个UI或者当前Canvas上,Update中写入LookA函数
// Update is called once per frame
void Update () {
transform.LookAt(Camera.main.transform);
}