写个unity的寻路算法
时间: 2023-09-26 13:08:00 浏览: 108
基于unity实现可视化A寻路算法源码.zip
Unity中的寻路算法通常使用A*算法。下面是一个简单的示例代码:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinding : MonoBehaviour
{
public Transform seeker, target; // 寻路起点和终点
Grid grid; // 网格
void Awake()
{
grid = GetComponent<Grid>();
}
void Update()
{
FindPath(seeker.position, target.position);
}
void FindPath(Vector3 startPos, Vector3 targetPos)
{
Node startNode = grid.NodeFromWorldPoint(startPos);
Node targetNode = grid.NodeFromWorldPoint(targetPos);
List<Node> openSet = new List<Node>();
HashSet<Node> closedSet = new HashSet<Node>();
openSet.Add(startNode);
while (openSet.Count > 0)
{
Node currentNode = openSet[0];
for (int i = 1; i < openSet.Count; i++)
{
if (openSet[i].fCost < currentNode.fCost || (openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost))
{
currentNode = openSet[i];
}
}
openSet.Remove(currentNode);
closedSet.Add(currentNode);
if (currentNode == targetNode)
{
RetracePath(startNode, targetNode);
return;
}
foreach (Node neighbor in grid.GetNeighbors(currentNode))
{
if (!neighbor.walkable || closedSet.Contains(neighbor))
{
continue;
}
int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor);
if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor))
{
neighbor.gCost = newMovementCostToNeighbor;
neighbor.hCost = GetDistance(neighbor, targetNode);
neighbor.parent = currentNode;
if (!openSet.Contains(neighbor))
{
openSet.Add(neighbor);
}
}
}
}
}
void RetracePath(Node startNode, Node endNode)
{
List<Node> path = new List<Node>();
Node currentNode = endNode;
while (currentNode != startNode)
{
path.Add(currentNode);
currentNode = currentNode.parent;
}
path.Reverse();
grid.path = path;
}
int GetDistance(Node nodeA, Node nodeB)
{
int dstX = Mathf.Abs(nodeA.gridX - nodeB.gridX);
int dstY = Mathf.Abs(nodeA.gridY - nodeB.gridY);
if (dstX > dstY)
{
return 14 * dstY + 10 * (dstX - dstY);
}
else
{
return 14 * dstX + 10 * (dstY - dstX);
}
}
}
```
该脚本需要与一个名为“Grid”的脚本一起使用,该脚本负责生成网格和节点。使用A*算法寻找路径时,需要首先根据起点和终点获取起点和终点所在的节点,然后使用openSet和closedSet分别存储已经遍历的节点和未遍历的节点。进入while循环后,每次从openSet中获取fCost最小的节点,然后检查是否到达终点,如果是,则回溯路径;如果不是,则将该节点周围的节点加入openSet。在加入openSet之前,需要计算每个节点的gCost和hCost,分别表示从起点到当前节点的实际代价和从当前节点到终点的估算代价。最终得到的路径是一系列节点的列表,可以在Grid脚本中进行渲染。
阅读全文