一、前言
在我们小组的项目的城市游戏场景中,我进行了车辆寻路的代码实现,该博客将简单记录一下工作内容。
二、代码实现
PathFinding:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
namespace PolyPerfect.City
{
public class PathFinding : MonoBehaviour
{
private BinaryHeap Open =new BinaryHeap(2048);
private Dictionary<Guid, int> OpenIDs = new Dictionary<Guid, int>();
private Dictionary<Guid, PathNode> Closed = new Dictionary<Guid, PathNode>();
[HideInInspector]
public List<Path> PathList = new List<Path>();
[HideInInspector]
public List<Path> wholePath;
private Vector3 startPoint;
private Vector3 endPoint;
private Tile endTile;
private Tile startTile;
private Guid endId;
public List<Path> GetPath(Vector3 start, Vector3 end, PathType pathType)
{
Open.Clear();
PathList = new List<Path>();
Closed.Clear();
OpenIDs.Clear();
startPoint = start;
endPoint = end;
startTile = FindClosestTile(startPoint, pathType);
endTile = FindClosestTile(endPoint, pathType);
List<Path> startPaths;
if(pathType == PathType.Sidewalk)
{
startPaths = startTile.sidewalkPaths;
}
else
startPaths = startTile.paths;
foreach (Path path in startPaths)
{
float h = CalculateHeuristic(path.pathPositions[path.pathPositions.Count - 1].position);
float g = Vector3.Distance(transform.position, path.pathPositions[0].position) + Vector3.Distance(transform.position, path.pathPositions[path.pathPositions.Count-1].position);
PathNode node = new PathNode() {
path = path, lastNode = null, currentScore = g, score = h +g};
Open.Insert(node);
OpenIDs.Add(node.path.Id, 0);
}
if(DoBfsSteps())
{
Closed[endId].path = FindClosestPath(endPoint, Closed[endId].lastNode.path.nextPaths);
GetPathList(Closed[endId]);
PathList.Reverse();
//PathList[0] = FindClosestPath(startPoint, startPaths);
return PathList;
}
else
{
return null;
}
}
public List<Path> GetPathWithCheckpoints(List<Vector3> checkpoints, PathType pathType)
{
wholePath = new List<Path>();
for (int i = 1; i < checkpoints.Count ;i++)
{
startPoint = checkpoints[i-1];
endPoint