Search code examples
c#unity-game-enginemultidimensional-arraypath-finding

Unity3D [intermediate] how to convert a List<nodes> .toArray? (pathfinding)


[EDIT] My issue wasn't solve by converting a List .toArray, but you can't find the way to do it in the answer given by @KBaker. Good luck!

-----------------------------------------------------------------------------------------------------------------------------------

I've been looking for topics and solutions here and on the Unity website, I didn't find something similar to my issue and am struggling since two weeks so please don't score this topic down for free. Thank you in advance!

As you can see on the following picture, my unit has orthogonal-only movements:

pathExample

That comes from SymplifyPath() in my Pathfinding script:

IEnumerator FindPath(Vector3 startPos, Vector3 targetPos){
    Vector3[] finalPath = new Vector3[0];
    bool pathSuccess = false;
    [...]//body
    yield return null;
    if (pathSuccess){
        finalPath = RetracePath(startNode, targetNode);
    }
    pathQueue.FinishedProcessingPath(finalPath, pathSuccess);
}

Vector3[] RetracePath(Nodes startNode, Nodes endNode){
    List<Node> path = new List<Node>();
    Node currentNode = endNode;
    while (currentNode != startNode){
        path.Add(currentNode);
        currentNode = currentNode.parent;
    }
    Vector3[] finalPath = SymplifyPath(path);
    Array.Reverse(finalPath);
    return finalPath;
}

Vector3[] SymplifyPath(List<Nodes> path){
    List<Vector3> finalPath = new List<Vector3>();
    Vector2 directionOld = Vector2.zero;
    for(int i = 1; i < path.Count; i++){
        Vector2 directionNew = new Vector2(path[i - 1].gridX - path[i].gridX, path[i - 1].gridZ - path[i].gridZ);{
            finalPath.Add(path[i - 1].worldPosition);
        }
        directionOld = directionNew;
    }
    return finalPath.ToArray();
}

In the line waypoints.Add(path[i - 1].worldPosition);, having -1 makes orthogonal-only movements. Without -1, paths have smoother movements but its path doesn't care about the middle of each nodes anymore and goes through walls. Without SimplyPath(), the original path cares about diagonals, middle of nodes and doesn't go through walls. That's exactly what I'm looking for.

Is it possible to use SimplifyPath() to convert the list of nodes located in RetracePath to arrays, without creating a new simplified path?

I'm thinking about something like:

Vector3[] SymplifyPath(List<Nodes> path){
    List<Vector3> finalPath = new List<Vector3>();
    Vector2 nodesListPath = Vector2.zero;
    for(int i = 1; i < path.Count; i++)
        {
            finalPath(path[i].worldPosition)
        }
        finalPath = nodesListPath;
    }
    return finalPath.ToArray();
}

Any ideas?


Solution

  • You can check out this website or this one to convert your list to an array.