Unity NavMeshAgent 进度获取:剩余路程比例(两位小数)
Unity NavMeshAgent 进度获取:剩余路程比例(两位小数)
本教程将演示如何使用 Unity 和 NavMeshAgent 组件获取并显示剩余路程占总路程的比例,并将结果格式化为两位小数。
**代码示例:**csharpNavMeshAgent agent;
void Start(){ agent = GetComponent
void Update(){ if (agent.pathPending) return;
float totalDistance = GetTotalDistance(agent.path); float remainingDistance = agent.remainingDistance;
float progress = Mathf.Clamp01(1f - remainingDistance / totalDistance); string progressText = progress.ToString('F2'); Debug.Log('Progress: 0.' + progressText);}
float GetTotalDistance(NavMeshPath path){ float totalDistance = 0f;
for (int i = 0; i < path.corners.Length - 1; i++) { totalDistance += Vector3.Distance(path.corners[i], path.corners[i + 1]); }
return totalDistance;}
代码解释:
- 获取 NavMeshAgent 组件: 在
Start()函数中,获取附加到游戏对象的NavMeshAgent组件实例。2. 检查路径计算: 在Update()函数中,首先检查agent.pathPending属性。如果为true,则表示 NavMesh 仍在计算路径,此时不进行计算。3. 计算总路程: 调用GetTotalDistance()函数计算路径的总长度。该函数遍历路径的所有拐角点,并累加相邻拐角点之间的距离。4. 计算剩余路程比例: 使用公式progress = 1 - (remainingDistance / totalDistance)计算剩余路程所占比例,并使用Mathf.Clamp01()将结果限制在 0 到 1 之间。5. 格式化输出: 使用ToString('F2')将比例值格式化为带有两位小数的字符串。6. 输出进度: 使用Debug.Log()将格式化的进度值输出到控制台。
注意事项:
- 在使用 NavMeshAgent 之前,请确保已在场景中烘焙 NavMesh,并且为代理设置了有效的目标位置。* 可以根据需要修改代码,将进度值显示在 UI 文本组件中,或用于其他游戏逻辑。
原文地址: https://www.cveoy.top/t/topic/WFd 著作权归作者所有。请勿转载和采集!