Files
valheim/Assets/_Valheim/Scripts/Player/GuideArrowPath.cs
2025-07-04 14:16:14 +08:00

84 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(LineRenderer))]
public class GuideArrowPath : NetworkBehaviour
{
// 内部变量
private NavMeshPath navPath;
private LineRenderer lineRenderer;
void Start()
{
// 获取LineRenderer组件
lineRenderer = GetComponent<LineRenderer>();
// 初始化NavMeshPath
navPath = new NavMeshPath();
// 尝试第一次更新路径
}
/// <summary>
/// 根据起点与终点计算最短路径并更新Line Renderer的显示
/// </summary>
public void SetPath(Vector3 start, Vector3 end)
{
navPath = new NavMeshPath();
// 使用NavMesh计算路径静态障碍物会自动参与计算
if (NavMesh.CalculatePath(start, end, NavMesh.AllAreas, navPath))
{
// 如果计算出有效路径且路径点数量大于1则更新LineRenderer
if (navPath.corners.Length > 1)
{
lineRenderer.positionCount = navPath.corners.Length;
List<Vector3> path = new List<Vector3>();
foreach (Vector3 point in navPath.corners)
{
path.Add(new Vector3(point.x,0.5f,point.z));
}
lineRenderer.SetPositions(path.ToArray());
}
else
{
lineRenderer.positionCount = 0;
}
}
else
{
Debug.LogWarning("未能计算出有效路径!");
lineRenderer.positionCount = 0;
}
}
public float GetToTargetDis(Vector3 start, Vector3 end)
{
float dis = -1;
if (NavMesh.CalculatePath(start, end, NavMesh.AllAreas, navPath))
{
if (navPath.corners.Length > 1)
{
dis = 0;
for (int i = 0; i < navPath.corners.Length; i++)
{
if (i + 1 < navPath.corners.Length)
{
dis+= Vector3.Distance(navPath.corners[i], navPath.corners[i + 1]);
}
}
}
}
return dis;
}
public void ShowPath()
{
gameObject.GetComponent<LineRenderer>().enabled = true;
}
public void ClosePath()
{
gameObject.GetComponent<LineRenderer>().enabled = false;
}
}