Esempio n. 1
0
        //Add a node to a parent node, ignoring if impassable or already closed,
        //adding if new, updating if new and better route
        private RouteNode AddAdjacentNode(int dx, int dy, int cost, RouteNode parent)
        {
            int x       = parent.X + dx;
            int y       = parent.Y + dy;
            int newCost = parent.MovementCost + cost;

            //Get terrain cost. -1 is not passable, 0 no cost, 1,2,3 etc higher cost
            int terraincost = GetTerrainCost(x, y);

            if (terraincost == -1)
            {
                return(null);
            }

            //Check if item has been added to the grid already
            RouteNode existing = (RouteNode)mGrid.Item(x, y);

            if (existing != null)
            {
                if (!existing.Closed && newCost < existing.MovementCost)
                {
                    existing.MovementCost = newCost;
                    existing.TotalCost    = existing.MovementCost + existing.Heuristic;
                    existing.Parent       = parent;

                    mOpenList.Update(existing);
                }
                return(existing);
            }

            //Create a new node
            RouteNode node = new RouteNode();

            node.Parent = parent;

            node.X = x;
            node.Y = y;

            node.MovementCost = newCost;                //Add the cost to the parent cost
            node.Heuristic    = GetHeuristic(node);
            node.TotalCost    = node.MovementCost + node.Heuristic;

            //Add terrain cost
            node.MovementCost += terraincost;
            node.TotalCost    += terraincost;

            //Set generation
            node.Generation = mGeneration;
            mGeneration++;

            //Add to the open list and the grid
            mOpenList.Push(node);
            mGrid.Add(node);

            return(node);
        }
Esempio n. 2
0
        //Check that a node can be created here
        private int GetTerrainCost(int x, int y)
        {
            //Check the boundary
            if (!mBoundary.Contains(x, y))
            {
                return(-1);
            }

            x = Convert.ToInt32(x / mGrain) * mGrain;
            y = Convert.ToInt32(y / mGrain) * mGrain;

            TerrainNode node = (TerrainNode)mTerrain.Item(x, y);

            if (node == null)
            {
                return(0);
            }

            return(node.MovementCost);
        }