_xiaofang/xiaofang/Assets/Script/UI/DistanceDisplay3D.cs
2024-10-21 10:08:49 +08:00

34 lines
1.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DistanceDisplay3D : MonoBehaviour
{
public Transform Character; // 玩家物体的 Transform
public Transform target; // 目标点物体的 Transform
public Text distanceText; // 3D Canvas 上显示距离的 Text 组件
private Transform canvasTransform; // 3D UI Canvas 的 Transform
void Start()
{
canvasTransform = distanceText.transform.parent; // 获取 Canvas 的 Transform
}
void Update()
{
// 计算玩家和目标之间的距离
float distance = Vector3.Distance(Character.position, target.position)-4;
// 更新 UI 显示距离,保留两位小数
distanceText.text = "距离目标: " + distance.ToString("F0") + " 米";
// 将 3D UI Canvas 移动到目标点上方,跟随目标点
canvasTransform.position = target.position + new Vector3(0, 5f, 0); // 在目标点上方 2 米
canvasTransform.LookAt(Character); // 让 3D UI 朝向玩家
canvasTransform.Rotate(0, 180, 0); // 反转 Canvas 的 y 轴,确保文字不被反转
}
}