findPath() public method

public findPath ( ) : void
return void
示例#1
0
文件: Mover.cs 项目: frms/game-jams
    public void findPath(Vector3 endPos)
    {
        Vector3 startPos = Map.map.mapToWorldPoint(reservedPos[0], reservedPos[1]);

        currentPath = AStar.findPath(Map.map, startPos, endPos, target, distToTarget);
        lastEndPos  = Map.map.worldToMapPoint(endPos);
    }
示例#2
0
    private void runAll(int i, int j)
    {
        var      start = new PathNode(new Vector2(i, j));
        PathNode goal  = null; //To get all routes.

        astar.findPath(start, goal);
    }
        public static Hallway getHallway(string id, Room previousRoom, Hallway previousHall, Room nextRoom, GameMap map, Random random, List <Position> wallPositions, List <Position> floorPositions)
        {
            int             triesToCreateExit = 0;
            List <Position> path     = new List <Position>();
            Position        entrance = new Position(); //Αρχικοποιήση πρως ικανοποίηση του compiler
            Position        exit     = new Position(); //Το ίδιο

            while (path.Count == 0)
            {
                entrance = createHallwayEntrance(previousRoom, previousHall, triesToCreateExit++, map, random);
                exit     = getExit(nextRoom, map, random);
                WalkableTile[,] walkableMap = initializeWalkable(map);
                path = AStar.findPath(entrance, exit, walkableMap);
            }

            List <Position> hallWallPositions = createWallPositions(path, entrance, exit, map);

            foreach (Position wallPosition in hallWallPositions)
            {
                if (!wallPositions.Contains(wallPosition))
                {
                    wallPositions.Add(wallPosition);
                }
            }
            floorPositions.AddRange(path);

            return(new Hallway(id, path, hallWallPositions));
        }
示例#4
0
文件: Map.cs 项目: frms/game-jams
    public void buildManualMap()
    {
        map = new MapData(mapWidth, mapHeight, tileSize);

        for (int x = 0; x < map.width; x++)
        {
            for (int y = 0; y < map.height; y++)
            {
                map.tiles[x, y] = 1;
            }
        }

        map.tiles[(map.width / 2) - 5, map.height / 2 + 3] = 2;

        player.position = map.mapToWorldPoint(map.width / 2, map.height / 2);

        Transform enemy1 = placeThing((map.width / 2) + 5, map.height / 2, enemyTypes[0]);
        Enemy1    e1     = enemy1.GetComponent <Enemy1>();

        e1.isLooping   = true;
        e1.currentPath = AStar.findPath(map, enemy1.position, enemy1.position + Vector3.up * map.tileSize * 7, null, 0);

        placeThing((map.width / 2) - 4, map.height / 2 - 1, enemyTypes[0]);

        placeThing((map.width / 2) - 6, map.height / 2 + 3, enemyTypes[1]);
    }
示例#5
0
    void redoAstar(bool rightArrow)
    {
        if (astar.path.Count > 0)
        {
            astar.path.Clear();
        }

        if (rightArrow)
        {
            if (endNodeIndex < this.nodeContainer.Count)
            {
                endNodeIndex++;
            }
        }
        else
        {
            if (endNodeIndex > 0)
            {
                endNodeIndex--;
            }
        }

        if (this.nodeContainer.Count == 0)
        {
            throw new System.Exception("Problem getting node container info.?");
        }

        cylinder.position = this.nodeContainer[startNodeIndex].worldPos;
        endGuy.position   = this.nodeContainer[endNodeIndex].worldPos;

        astar.findPath(this.nodeContainer[startNodeIndex], this.nodeContainer[endNodeIndex]);
        Debug.Log("endNodeIndex" + endNodeIndex.ToString());
    }
示例#6
0
 void FixedUpdate()
 {
     if (bg.stspt.click == true && walk == false)         //开始键被按下
     {
         InitGame();
         walk = true;
         if (astar.findPath(grid) == true)
         {
             findroad = true;
             //print(astar._path.Count);
         }
     }
     else if (walk == true && hasdone < astar._path.Count)
     {
         time += Time.deltaTime;
         Vector2 des;            //目的地
         des.x = astar._path[hasdone].x * 64 + 32;
         des.y = astar._path[hasdone].y * 64 + 50;
         if (WalkTo(des) == true)
         {
             hasdone++;
         }
     }
     if (hasdone >= astar._path.Count)
     {
         finish         = true;
         walk           = false;
         bg.stspt.click = false;
         //Destroy(gameObject);
         transform.localScale = new Vector3(0, 0, 0);
     }
 }
示例#7
0
    private void findPath(MapData graph, Vector3 startPos, Vector3 endPos, TeamMember target)
    {
        currentPath       = AStar.findPath(graph, startPos, endPos, target);
        farthestPathParam = float.NegativeInfinity;
        farthestPathTime  = Time.time;

        arriveStartTime = float.NegativeInfinity;
    }
示例#8
0
 void initializePaths()
 {
     for (int i = 0; i < startNodes.Length; i++)
     {
         paths.Add(new Path());
         paths[i].points = AStar.findPath(nodes[(int)startNodes[i].x, (int)startNodes[i].y], nodes[(int)goalNodes[i].x, (int)goalNodes[i].y]);
     }
 }
示例#9
0
 // Update is called once per frame
 void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         Vector2 mouseposition = Input.mousePosition;
         int     xpos          = (int)Mathf.Floor(mouseposition.x / 20);
         int     ypos          = (int)Mathf.Floor((Screen.height - mouseposition.y) / 20);
         _grid.SetWalkbale(xpos, ypos, !_grid.getNode(xpos, ypos).walkbale);
         astar.findPath(_grid);
     }
 }
示例#10
0
 /*
  * so everything here is fixed that it clears if not running resets values
  * and can redo a new path if the old one isnt running anymore
  */
 void AstarPather(Vector3 currentPos, Vector3 targetPos)
 {
     points.Clear();
     newPath = path.findPath(currentPos, targetPos);
     foreach (Node n in newPath)
     {
         Vector3 newDirection = n.worldPosition;
         points.Add(newDirection);
     }
     coroutine = runPath(points);
     StopAllCoroutines();
     StartCoroutine(coroutine);
 }
示例#11
0
	// Use this for initialization
	void Start () {
	   _grid = new Grid(50,30);
	   _grid.SetStartNode(0,2);
	   _grid.SetEndNode(48,10);
	   astar = new AStar();
	   if(astar.findPath(_grid))
	   {
		   for(int i = 0; i<astar._path.Count;i++)
		   {
			     text += "("+astar._path[i].x+","+astar._path[i].y+")"+"  ";
		   }
		   Debug.Log(text);
	   }
	}
    public List <Vector3> GetPath(Point startPoint, Point endPoint, float carangle)
    {
        this.aStar = new AStar(grid);
        aStar.init(startPoint.x - grid.xlow, startPoint.y - grid.zlow, endPoint.x - grid.xlow, endPoint.y - grid.zlow, carangle);
        aStar.findPath();
        List <Vector3> path = new List <Vector3>();

        for (int i = aStar.result.Count - 1; i >= 0; i--)
        {
            Node n = aStar.result[i];
            path.Add(new Vector3(startPoint.x + (n.location.x - aStar.result[aStar.result.Count - 1].location.x) + 0.5f, 0.5f, startPoint.y + (n.location.y - aStar.result[aStar.result.Count - 1].location.y) + 0.5f));
        }
        return(path);
    }
示例#13
0
    public override Action GetAction()
    {
        PlayerActor target = FindObjectOfType <PlayerActor>();
        AStar       a      = GetAStar(BoardPosition, target.BoardPosition);

        a.findPath();
        if (a.solution.Count > 1)
        {
            AStarNode2D node      = (AStarNode2D)a.solution[1];
            IntVector2  direction = IntVector2.GetDirection(node.x - BoardPosition.X, node.y - BoardPosition.Y);
            return(GetMoveAction(direction));
        }
        return(GetComponent <DoNothingAction>());
    }
示例#14
0
 // Use this for initialization
 void Start()
 {
     _grid = new Grid(50, 30);
     _grid.SetStartNode(0, 2);
     _grid.SetEndNode(48, 10);
     astar = new AStar();
     if (astar.findPath(_grid))
     {
         for (int i = 0; i < astar._path.Count; i++)
         {
             text += "(" + astar._path[i].x + "," + astar._path[i].y + ")" + "  ";
         }
         Debug.Log(text);
     }
 }
示例#15
0
    // Update is called once per frame
    public virtual void Update()
    {
        checkForDeath();
        if (timeToDisappear != Mathf.Infinity || IAmBeingEaten)
        {
            return;
        }

        if (isLooping && currentPath != null && isAtEndOfPath())
        {
            currentPath = AStar.findPath(Map.map, currentPath.endNode, currentPath[0], null, 0);
        }

        moveUnit();
    }
示例#16
0
    //MoveEnemy is called by the GameManger each turn to tell each Enemy to try to move towards the player.
    private void MoveEnemyToPlayer()
    {
        //GetComponent<BoxCollider2D>().enabled = false;
        //playerTransform.GetComponent<BoxCollider2D>().enabled = false;

        astar = new AStar(new StoredArrayAStarCost(_boardCreator), currentX, currentY, Mathf.RoundToInt(playerTransform.position.x), Mathf.RoundToInt(playerTransform.position.y));
        astar.findPath();
        AStarNode2D nextStep = (AStarNode2D)astar.solution[1];

        //GetComponent<BoxCollider2D>().enabled = true;
        //playerTransform.GetComponent<BoxCollider2D>().enabled = true;

        int xDir = nextStep.x - currentX;
        int yDir = nextStep.y - currentY;

        AttemptMove <Player>(xDir, yDir);
    }
示例#17
0
    private void findPathToPlayer()
    {
        int[] end = new int[2];
        end [0] = Mathf.FloorToInt(player.position.x);
        end [1] = Mathf.FloorToInt(player.position.y);

        if (currentPath == null || lastPlayerPos == null || lastPlayerPos [0] != end [0] || lastPlayerPos [1] != end [1])
        {
            int[] start = new int[2];
            start [0] = Mathf.FloorToInt(transform.position.x);
            start [1] = Mathf.FloorToInt(transform.position.y);

            currentPath = AStar.findPath(map, start, end);

            lastPlayerPos = end;
        }
    }
        public override void run()
        {
            if (target == null)
            {
                actor.force = Vector2.Zero;
                return;
            }

            Vector2 playerpos = (actor.world as GameWorld).player.position;
            Vector2 moveDir   = playerpos - actor.position;

            if (moveDir.Length() < radius)
            {
                moveDir = -moveDir;
            }

            Vector2 dest = AStar.findPath(actor.world, new Rectangle((int)(actor.position.X - actor.size / 2), (int)(actor.position.Y - actor.size / 2), (int)actor.width, (int)actor.height),
                                          new Rectangle((int)(target.position.X - target.size / 2), (int)(target.position.Y - target.size / 2), (int)target.width, (int)target.height));

            if (dest == Vector2.Zero)
            {
                canSee = true;
                //dest = target.position;
            }
            else
            {
                canSee = false;
            }
            if (moveDir.LengthSquared() > radius)//if outside radius
            {
                inRange = false;
            }
            else if (moveDir.LengthSquared() < radius + 10)//if inside the radius
            {
                moveDir *= -1;
                inRange  = false;
            }
            else//if inside the radius
            {
                moveDir = Vector2.Zero;
                inRange = true;
            }
            moveDir         = Vector2.Normalize(moveDir);
            actor.position += moveDir * speed;
        }
示例#19
0
        public AStarNode[] findPath(int startX, int startY, int endX, int endY)
        {
            m_grid.setStartNode(startX, startY);
            m_grid.setEndNode(endX, endY);
            bool find = m_astar.findPath(m_grid);

            if (find)
            {
                AStarNode[] path = new AStarNode[m_astar.path.Length - 1];
                for (int i = 0; i < path.Length; i++)
                {
                    path[i] = m_astar.path[i + 1];
                }

                return(path);
            }
            return(null);
        }
示例#20
0
 void FixedUpdate()
 {
     if (bg.stspt.click == true && walk == false)
     //if (Input.GetButton ("Jump"))
     {        //开始键被按下
         InitGame();
         walk = true;
         if (astar.findPath(grid) == true)
         {
             findroad = true;
             //print(astar._path.Count);
         }
     }
     else if (walk == true && hasdone < astar._path.Count)
     {
         time += Time.deltaTime;
         Vector2 des;            //目的地
         des.x = astar._path[hasdone].x * 64 + 32;
         des.y = astar._path[hasdone].y * 64 + 50;
         //print(astar._path[hasdone].x + " " + astar._path[hasdone].y);
         if (WalkTo(des) == true)
         {
             hasdone++;
         }
     }
     if (hasdone >= astar._path.Count)
     {
         if (finish == false)
         {
             ;
         }
         //bg.sco+= bg.level*100;
         finish = true;
         walk   = false;
         transform.localScale = new Vector3(0, 0, 0);
         bg.stspt.click       = false;
         //Destroy(gameObject);
     }
 }
示例#21
0
    //MoveEnemy is called by the GameManger each turn to tell each Enemy to try to move towards the player.
    private void MoveEnemyToRandom()
    {
        Vector2 targetVector = _boardCreator.GetRandomTileLocation();

        //Prevent rolling the exact same position
        while (targetVector.x == currentX && targetVector.y == currentY)
        {
            targetVector = _boardCreator.GetRandomTileLocation();
        }

        astar = new AStar(new StoredArrayAStarCost(_boardCreator), currentX, currentY, Mathf.RoundToInt(targetVector.x), Mathf.RoundToInt(targetVector.y));
        astar.findPath();

        //Set flags to tell MoveEnemy() that we successfully computed location
        astarCounter = 1;

        AStarNode2D nextStep = (AStarNode2D)astar.solution[astarCounter];

        int xDir = nextStep.x - currentX;
        int yDir = nextStep.y - currentY;

        AttemptMove <Player>(xDir, yDir);
    }
示例#22
0
        public override void run()
        {
            if (target == null)
            {
                actor.force = Vector2.Zero;
                return;
            }

            // Run A*
            Vector2 dest = AStar.findPath(actor.world, new Rectangle((int)(actor.position.X - actor.width / 2), (int)(actor.position.Y - actor.height / 2), (int)actor.width, (int)actor.height),
                                          new Rectangle((int)(target.position.X - target.width / 2), (int)(target.position.Y - target.height / 2), (int)target.width, (int)target.height));

            if (dest == Vector2.Zero)
            {
                canSee = true;
                dest   = target.position;
            }
            else
            {
                canSee = false;
            }

            actor.force += Vector2.Normalize(dest - actor.position) * force;
        }
        /// <summary>
        /// Updates pathfinding every fixed update (currently 0.02 in project
        /// settings).
        /// </summary>
        private void FixedUpdate()
        {
            // Can be stunned, but not hurt. He is immortal. Only death can free you of debt.
            // (Or, ya' know, paying off your debt.)
            if (player == null || stunned)
            {
                return;
            }

            // Figure out the vectors for where to head to.
            Vector3 playerDirection     = (player.transform.position - transform.position).normalized;
            Vector3 flatPlayerDirection = new Vector3(playerDirection.x, 0, playerDirection.z);
            Vector2 flatPosition        = new Vector2(transform.position.x, transform.position.z);
            Vector2 playerFlatPosition  = new Vector2(player.transform.position.x, player.transform.position.z);

            distanceFromPlayer2D = Vector2.Distance(playerFlatPosition, flatPosition);

            saveCounter++;

            // Apply gravity as needed.
            setVerticalMovement();

            // DC has been in the same cell for too long
            // But we don't want to teleport when we're really close to the player
            if (saveCounter >= teleportationSaveRate && distanceFromPlayer2D > minDistanceFromPlayerToTeleport)
            {
                // Easy to determine teleportation destination when the path is filled.
                if (path != null && path.Count > 0)
                {
                    if (nextDestinationNode == null)
                    {
                        // Grab the next destination from the path.
                        nextDestinationNode = path.Pop();
                    }

                    // Turn off the character controller.
                    controller.enabled = false;

                    // Teleport to the nextDestinationNode (at 80% of max height).
                    verticalSpeed      = 0f;
                    airborne           = true;
                    transform.position = new Vector3(nextDestinationNode.x, teleportationHeight, nextDestinationNode.y);

                    // Turn on the character controller again.
                    controller.enabled = true;

                    // If don't reset this value, gets stuck because never entered via the colliders.
                    lastVisitedNode = nextDestinationNode;

                    // Set a new destination or prepare to recalculate the path.
                    if (path.Count > 0)
                    {
                        nextDestinationNode = path.Pop();
                    }

                    else
                    {
                        path = null;
                        recalculationCount = 0;
                    }
                }

                else
                {
                    // Determine a valid cell to transport to.
                    Vertex teleportTo = lastVisitedNode.cell.neighbors.First(c => c.reachable).site;

                    // Move the debt collector to the location.
                    controller.enabled = false;
                    transform.position = new Vector3(teleportTo.x, teleportationHeight, teleportTo.y);
                    controller.enabled = true;
                    lastVisitedNode    = teleportTo;

                    // In case the path count was 0 but the path wasn't yet set to null.
                    if (path != null)
                    {
                        path = null;
                        recalculationCount = 0;
                    }
                }

                // Now at a new location, so can reset the counter.
                saveCounter = 0;
                return;
            }

            // Straight line pursuit. Want to catch player, so no retreat.
            if (distanceFromPlayer2D < visionRadius)
            {
                // Unlikely that the path will be valid if player gets away.
                if (path != null)
                {
                    path = null;
                    recalculationCount = 0;
                }

                // Obtain the "safe" direction to go.
                Vector3 safeDir = findSafeDirection(flatPlayerDirection);

                // Draw the direction to the player.
                #if UNITY_EDITOR
                Debug.DrawRay(transform.position, safeDir * whiskerLength, Color.black, 1);
                #endif

                applyMovement(safeDir);
                return;
            }

            if (path == null)
            {
                // Because script execution order apparently means nothing now.
                if (hivemind.lastPlayerLocation == null)
                {
                    return;
                }

                // DEBUG: Remove.
                #if UNITY_EDITOR
                //Debug.Log("RECALCULATING PATH.");
                #endif
                path = pathfinder.findPath(lastVisitedNode, hivemind.lastPlayerLocation);

                // Was extremely close to destination. A path was not needed.
                if (path.Count == 0)
                {
                    path = null;
                    return;
                }

                // DEBUG: Uncomment if behavior is unexpected.
                // outputPathToFile();

                // Start navigating path by obtaining first vertex.
                nextDestinationNode = path.Pop();

                // DEBUG: Remove or set debugging code.
                #if UNITY_EDITOR
                //Debug.Log("NEXT DESTINATION: " + nextDestinationNode.vector);
                #endif

                nextDestination = new Vector3(nextDestinationNode.x, transform.position.y, nextDestinationNode.y);
                Vector3 unnormDirection = nextDestination - transform.position;
                nextFlatDir = new Vector3(unnormDirection.x, 0, unnormDirection.z).normalized;

                return;
            }

            // Prepare for recalculation of path.
            if (recalculationCount >= recalculationRate)
            {
                path = null;
                recalculationCount = 0;
            }

            // Obtain next node or prepare for recalculation if triggered zone site and destination are equal.
            if (lastVisitedNode.Equals(nextDestinationNode))
            {
                // Deal with unknown null path.
                if (path == null)
                {
                    return;
                }

                if (path.Count > 0)
                {
                    nextDestinationNode = path.Pop();

                    // DEBUG: Remove or set debugging code.
                    #if UNITY_EDITOR
                    //Debug.Log("NEXT DESTINATION: " + nextDestinationNode.vector);
                    #endif

                    nextDestination = new Vector3(nextDestinationNode.x, transform.position.y, nextDestinationNode.y);
                    Vector3 unnormDirection = nextDestination - transform.position;
                    nextFlatDir = new Vector3(unnormDirection.x, 0, unnormDirection.z).normalized;

                    Vector3 safeDir = findSafeDirection(nextFlatDir);

                    // Move in the safe direction.
                    applyMovement(safeDir);

                    // Because used pathfinding, must get closer to recalculation.
                    recalculationCount++;
                    return;
                }

                // Want to recalculate the path, as already reached our destination.
                path = null;
                recalculationCount = 0;
                return;
            }

            // Find the safe direction and move there.
            Vector3 safeDirection = findSafeDirection(nextFlatDir);
            applyMovement(safeDirection);
            recalculationCount++;
        }
 //move the object to a space provided it is not full
 private void moveToSpace(int[] xzy)
 {
     if (!grid.getGameObjByCoords(xzy).GetComponent<GridCell>().isEmpty()) {
         return;
     }
     AStar pathFinder = new AStar();
     pathFinder.findPath(grid.getGameObjByCoords(mycells[0]).GetComponent<GridCell>(), grid.getGameObjByCoords(xzy).GetComponent<GridCell>(), grid.cells);
     List<KeyValuePair<float,int>> dirs = cellsToDirs(pathFinder.cellsFromPath());
     StartCoroutine(rotateAndMoveObject(dirs));
     string s = "";
     foreach(KeyValuePair<float,int> dir in dirs) {
         s += dir.Key + "," + dir.Value + " ";
     }
     Debug.Log(s);
 }
示例#25
0
        public ActionResult setPath(int x, int y)
        {
            Console.WriteLine("Set path, X: " + x + " Y: " + y);

            List <Location> testL = new List <Location>();

            int act = 0;

            foreach (var l in _context.Location)
            {
                testL.Add(l);
            }

            List <Location> updatedTestL = new List <Location>();
            LocationGroup   lg           = new LocationGroup {
                locations = testL
            };
            Grid model = new Grid {
                action = 0, cId = 0, grid = lg
            };

            var a = _context.G;

            foreach (var ac in a)
            {
                if (x == 100 && y == 100)
                {
                    ac.action = 1;
                }
                else if (x == 101 && y == 101)
                {
                    ac.action = 2;
                }
                else if (x == 102 && y == 102)
                {
                    ac.action = 3;
                }
                else if (x == 103 && y == 103)
                {
                    ac.action = 0;
                }
                else if (x == 104 && y == 104)
                {
                    AStar findPath = new AStar(testL);
                    Console.WriteLine("CHECK B");
                    updatedTestL = findPath.findPath();
                    Console.WriteLine("CHECK G");
                }
                _context.SaveChanges();
                act = ac.action;
            }


            if (x != 104)
            {
                Location rip = new Location {
                    XLoc = 0, YLoc = 0, myD = 0
                };

                foreach (var l in model.grid.locations)
                {
                    if (l.XLoc == x && l.YLoc == y)
                    {
                        rip = new Location {
                            XLoc = l.XLoc, YLoc = l.YLoc, myD = act
                        };
                        l.myD = act;
                        _context.SaveChanges();
                        updatedTestL.Add(rip);
                    }
                    else
                    {
                        updatedTestL.Add(l);
                    }
                }
            }

            model.grid.locations = updatedTestL;
            return(View("Index", model));
        }
示例#26
0
文件: Mover.cs 项目: frms/game-jams
    internal void moveUnit()
    {
        if (target != null)
        {
            findPathToUnit();
        }

        Vector2 accel = Vector2.zero;

        bool standStill = false;

        if (currentPath != null)
        {
            Vector2 targetPosition;

            accel = steerTowardsPath(out targetPosition);

            int[] mapPos = Map.map.worldToMapPoint(targetPosition);

            if (!equals(mapPos, reservedPos))
            {
                if (Map.map.getObj(mapPos) == null)
                {
                    Map.map.setObj(reservedPos, null);
                    Map.map.setObj(mapPos, this);
                    reservedPos = mapPos;
                }
                else
                {
                    //Debug.Log (name + " is moving onto an occupied node");

                    int i = findNextUnoccupiedNode(targetPosition);

                    // Should prob change the if to find path to target and get as close as possible
                    // and make the else code happen outside of the else block
                    if (i == currentPath.Length)
                    {
                        //Debug.Log(name + " has no unoccupied nodes on its current path to its goal");
                        standStill = true;
                    }
                    else
                    {
                        Vector3 startPos = Map.map.mapToWorldPoint(reservedPos[0], reservedPos[1]);
                        Vector3 endPos   = currentPath[i];

                        LinePath detour = AStar.findPath(Map.map, startPos, endPos, null, 0, false);

                        /* If we can't find a detour path just find a way to the end node */
                        if (detour == null)
                        {
                            //Debug.Log (name + " no detour to next open space. Finding new path to end goal all together.");
                            currentPath = AStar.findPath(Map.map, currentPath[0], currentPath.endNode, null, 0, false);
                        }
                        /* Else update the current path */
                        else
                        {
                            //Vector3[] newNodes = new Vector3[detour.Length + (currentPath.Length - i - 1)];

                            List <Vector3> newNodes = new List <Vector3>();

                            for (int j = 0; j < currentPath.Length; j++)
                            {
                                if (currentPath[j] != startPos)
                                {
                                    newNodes.Add(currentPath[j]);
                                }
                                else
                                {
                                    break;
                                }
                            }

                            for (int j = 0; j < detour.Length; j++)
                            {
                                newNodes.Add(detour[j]);
                            }

                            i = i + 1;
                            for (; i < currentPath.Length; i++)
                            {
                                newNodes.Add(currentPath[i]);
                            }

                            currentPath = new LinePath(newNodes.ToArray());
                        }

                        accel = steerTowardsPath(out targetPosition);
                    }
                }
            }
        }
        else
        {
            standStill = true;
        }

        if (standStill)
        {
            accel = steeringUtils.arrive(Map.map.mapToWorldPoint(reservedPos [0], reservedPos [1]));
        }

        steeringUtils.steer(accel);
        steeringUtils.lookWhereYoureGoing();
    }
示例#27
0
    // Use this for initialization
    void Start()
    {
        nodePositions = new List <Vector3>();
        nodeContainer = new List <Node>();

        verts = NavMesh.CalculateTriangulation().vertices;
        int[] indicies = NavMesh.CalculateTriangulation().indices;
        nmtri = NavMesh.CalculateTriangulation();

        g = new Graph();

        //Add Nodes
        Vector3 ctoid = new Vector3();

        for (int k = 0; k < nmtri.vertices.Length - 2; ++k)
        {
            ctoid = getCentroid(nmtri.vertices[k], nmtri.vertices[k + 1], nmtri.vertices[k + 2]);
            nodePositions.Add(ctoid);
            Node reff = g.AddNode("Node: " + k.ToString(), k, ctoid);
            nodeContainer.Add(reff);
        }

        Vector3 toid = new Vector3();
        int     jj   = verts.Length;

        toid = getCentroid(nmtri.vertices[jj - 3], nmtri.vertices[jj - 2], nmtri.vertices[jj - 1]);
        nodePositions.Add(toid);
        Node refff = g.AddNode("Node: " + (jj - 2).ToString(), jj - 2, toid);

        nodeContainer.Add(refff);

        Debug.Log("Added Nodes to Graph.\n");
        Debug.Log(verts.Length);
        //Add edges

        /*
         * for (int t = 0; t < nodeContainer.Count - 15; ++t)
         * {
         *  for (int tt = 0; tt < nodeContainer.Count - (10); ++tt)
         *  {
         *      Node n = nodeContainer[t];
         *      Node no = nodeContainer[tt];
         *      if (n != no)
         *      {
         *          double dist = Mathf.Sqrt(Mathf.Pow((n.worldPos.x - no.worldPos.x), 2) + Mathf.Pow((n.worldPos.z - no.worldPos.z), 2));
         *          Debug.Log("DISTANCE: " + dist.ToString());
         *          if (dist <= 45.0)
         *          {
         *              g.AddDirectedEdge("Node: "+t.ToString(), "Node: "+tt.ToString());
         *              //Debug.Log("Added Edge "+ "Node: " + t.ToString()+" "+ "Node: " + tt.ToString());
         *          }
         *      }
         *  }
         * }
         */


        /**/
        for (int j = 0; j < nodeContainer.Count - 2; ++j)
        {
            g.AddDirectedEdge("Node: " + (j).ToString(), "Node: " + (j + 1).ToString());
        }
        g.AddDirectedEdge("Node: 47", "Node: 0");
        g.AddDirectedEdge("Node: 43", "Node: 0");
        /**/


        Debug.Log("Added Edges to Graph.\n");

        // Begin Astar Pathfinding
        astar = new AStar(g, useHeap);

        if (this.nodeContainer.Count == 0)
        {
            throw new System.Exception("Problem getting node container info.?");
        }

        cylinder.position = this.nodeContainer[startNodeIndex].worldPos;
        endGuy.position   = this.nodeContainer[endNodeIndex].worldPos;

        astar.findPath(this.nodeContainer[startNodeIndex], this.nodeContainer[endNodeIndex]);
        Debug.Log("endNodeIndex" + endNodeIndex.ToString());
    }
    public void placeRivers()
    {
        int numBridges = ld.width/15 - 1;
        int numBridgesPlaced = 0;

        //Where does the river enter and exit the map? (horizontal only ATM)
        int entrance = (int) Mathf.Clamp(r.getIntInRange(3,ld.height-3),3,ld.height-1);
        int exit = (int) Mathf.Clamp(r.getIntInRange(3,ld.height-3),3,ld.height-1);

        Vector2 start = new Vector2(0, entrance);
        Vector2 end = new Vector2(ld.width-1, exit);

        // SET UP THE ASTAR
        astar = new AStar(ld.width, ld.height);
        astar.clearGrid();
        astar.allowDiagonals = true;
        astar.penalizeDirectionChanges = false;
        astar.setStartAndEnd(start, end);
        astar.THE_SEED = (float)ld.seed;
        astar.COVER_SCATTER = 0.1f;
        astar.randomCover((int)ld.seed);

        //The river winds around mountains and other solid stuff if it can
        GridNode[] thePath = astar.findPath();

        int placeABridgeCounter = r.getIntInRange(1,thePath.Length /numBridges+5);

        for(int i=0; i<thePath.Length; i++)
        {

            GridNode node = thePath[i];
            int x = (int)node.x;
            int y = (int)node.y;

            int yup = (int)Mathf.Max(y-1,0);
            int xup = (int)Mathf.Min(x+1,ld.width-1);

            if(numBridgesPlaced <= numBridges && placeABridgeCounter <= 0)
            {
                ld.placeTile(x,y,BRIDGE,-1, false);
                ld.placeTile(x,yup,BRIDGE,-1, false);
                ld.placeTile(xup,y,BRIDGE,-1, false);
                ld.placeTile(xup,yup,BRIDGE,-1, false);

                numBridgesPlaced ++;
                placeABridgeCounter = r.getIntInRange(1,thePath.Length /numBridges);
            }
            else
            {
                ld.placeTile(x,y,WATER,-1, true);
                ld.placeTile(x,yup,WATER,-1, true);
                ld.placeTile(xup,y,WATER,-1, true);
                ld.placeTile(xup,yup,WATER,-1, true);
            }
            placeABridgeCounter--;
        }//foreach
    }
示例#29
0
 void findFood()
 {
     current   = new Point(snakeHead.transform.position);
     foodPoint = new Point(foodPrefab.transform.position);
     path      = AStar.findPath(current, foodPoint);
 }