PathfindingManager.Closest C# (CSharp) Method

Closest() public static method

public static Closest ( List inNodes, Vector3 toPoint ) : int
inNodes List
toPoint Vector3
return int
    public static int Closest(List</*GameObject*/PathNode> inNodes, Vector3 toPoint)
    {
        int closestIndex = 0;
        float minDist = float.MaxValue;
        for(int i = 0; i < inNodes.Count; i++)
        {
            if(AStarHelper.Invalid(inNodes[i]/*.GetComponent<PathNode>()*/))
                continue;
            float thisDist = Vector3.Distance(toPoint, inNodes[i]/*.GetComponent<PathNode>()*/.Position);
            if(thisDist > minDist)
                continue;

            minDist = thisDist;
            closestIndex = i;
        }

        if (minDist != float.MaxValue)
            return closestIndex;
        else
            return -1;
    }

Usage Example

コード例 #1
0
    public void WaypointSystemChangedCallback()
    {
        WaypointManager wg         = GameObject.Find("WaypointManager").GetComponent <WaypointManager>();
        var             sources    = wg.pathNodes;
        int             startIndex = -1;
        int             endIndex   = -1;

        if (actualStartNode == null || !actualStartNode.nodeValid)
        {
            startIndex      = PathfindingManager.Closest(sources, startNodePosition);
            actualStartNode = sources[startIndex];
        }
        if (actualTargetNode == null || !actualTargetNode.nodeValid)
        {
            endIndex         = PathfindingManager.Closest(sources, endNodePosition);
            actualTargetNode = sources[endIndex];
        }

        bool found = false;

        if (path != null)
        {
            //foreach (PathNode pn in path)
            for (int i = 0; i < path.Count; i++)
            {
                PathNode pn = path[i];

                if (pn == null || !pn.nodeEnabled || !pn.nodeValid)
                {
                    found = true;
                    break;
                }
            }
            if (found)
            {
                path.Clear();
            }
        }
    }