Hello! I’m a beginner game developer and have been taking this course. I’ve encountered an issue with my move action. The problem appears when I include a path length check in my MoveAction.cs script. I’ve checked the code so many times and even tried copying the classes from GitLab, but the problem still persists.
If I remove the path length check from the code the move action works. so if I remove this block:
if (!Pathfinding.Instance.HasPath(unitGridPosition, testGridPosition, out int pathLength)) {
continue;
}
int pathFindingDistanceMultiplier = 10;
if (pathLength > (maxMoveDistance * pathFindingDistanceMultiplier)) {
continue;
}
To explain: I’ve made an “out” parameter from the hasPath() method to get the pathLength variable here instead of calling FindPath twice. I did that because the game got laggy, and I thought that might be the reason.
Here’s my HasPath() method in PathFinding.cs:
public bool HasPath(GridPosition startGridPosition, GridPosition endGridPosition, out int pathL) {
bool hasPath = FindPath(startGridPosition, endGridPosition, out int pathLength) != null;
pathL = pathLength;
return hasPath;
}
and the FindPath() method:
public List<GridPosition> FindPath(GridPosition startGridPosition, GridPosition endGridPosition, out int pathLength)
{
List<PathNode> openList = new List<PathNode>();
List<PathNode> closedList = new List<PathNode>();
PathNode startNode = gridSystem.GetGridObject(startGridPosition);
PathNode endNode = gridSystem.GetGridObject(endGridPosition);
openList.Add(startNode);
for (int x = 0; x < gridSystem.GetWidth(); x++)
{
for (int z = 0; z < gridSystem.GetHeight(); z++)
{
GridPosition gridPosition = new GridPosition(x, z);
PathNode pathNode = gridSystem.GetGridObject(gridPosition);
pathNode.SetGCost(int.MaxValue);
pathNode.SetHCost(0);
pathNode.CalculateFCost();
pathNode.ResetPredecessorPathNode();
}
}
startNode.SetGCost(0);
startNode.SetHCost(CalculateDistance(startGridPosition, endGridPosition));
startNode.CalculateFCost();
while (openList.Count > 0)
{
PathNode currentNode = GetLowestFCostPathNode(openList);
if (currentNode == endNode)
{
pathLength = endNode.GetFCost();
return CalculatePath(endNode);
}
openList.Remove(currentNode);
closedList.Add(currentNode);
foreach (PathNode neighbourNode in GetNeighbourList(currentNode))
{
if (closedList.Contains(neighbourNode))
{
continue;
}
if (!neighbourNode.IsWalkable()) {
closedList.Add(neighbourNode);
continue;
}
int tentativeGCost =
currentNode.GetGCost() + CalculateDistance(currentNode.GetGridPosition(), neighbourNode.GetGridPosition());
if (tentativeGCost < neighbourNode.GetGCost())
{
neighbourNode.SetPredecessorPathNode(currentNode);
neighbourNode.SetGCost(tentativeGCost);
neighbourNode.SetHCost(CalculateDistance(neighbourNode.GetGridPosition(), endGridPosition));
neighbourNode.CalculateFCost();
if (!openList.Contains(neighbourNode))
{
openList.Add(neighbourNode);
}
}
}
}
pathLength = 0;
return null;
}