示例#1
0
        ///<summary>
        ///use to add the eight neighboring edges of a graph node that 
        ///is positioned in a grid layout
        ///</summary>
        ///<param name="graph"></param>
        ///<param name="row"></param>
        ///<param name="col"></param>
        ///<param name="numCellsX"></param>
        ///<param name="numCellsY"></param>
        public static void AddAllNeighborsToGridNode(
            SparseGraph graph,
            int row,
            int col,
            int numCellsX,
            int numCellsY)
        {
            for (int i = -1; i < 2; ++i)
            {
                for (int j = -1; j < 2; ++j)
                {
                    int nodeX = col + j;
                    int nodeY = row + i;

                    //skip if equal to this node
                    if ((i == 0) && (j == 0)) continue;

                    //check to see if this is a valid neighbor
                    if (!ValidNeighbor(nodeX, nodeY, numCellsX, numCellsY))
                        continue;

                    //calculate the distance to this node
                    Vector2 posNode =
                        graph.GetNode(row*numCellsX + col).Position;
                    Vector2 posNeighbour =
                        graph.GetNode(nodeY*numCellsX + nodeX).Position;

                    float dist = (posNode - posNeighbour).Length();

                    //this neighbor is okay so it can be added
                    NavGraphEdge newEdge =
                        new NavGraphEdge(
                            row*numCellsX + col,
                            nodeY*numCellsX + nodeX,
                            dist);
                    graph.AddEdge(newEdge);

                    //if graph is not a digraph, an edge needs to be added going
                    //in the other direction
                    if (graph.IsDigraph)
                        continue;

                    NavGraphEdge newReverseEdge =
                        new NavGraphEdge(
                            nodeY*numCellsX + nodeX,
                            row*numCellsX + col,
                            dist);
                    graph.AddEdge(newReverseEdge);
                }
            }
        }