Пример #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Astar"/> class.
 /// </summary>
 /// <param name="p">The parent of the new Astar object</param>
 /// <param name="x">The x coordinate.</param>
 /// <param name="y">The y coordinate.</param>
 /// <param name="b">The grid of loations that have already been tested.</param>
 /// <param name="tx">The x coordinate of the target.</param>
 /// <param name="ty">The y coordinate of the target.</param>
 /// <param name="b">The grid of loations that are occupied by an obstacle.</param>
 public void Astarinit(Astar p, int x, int y, bool[][] b, int tx, int ty, bool[][] blocked)
 {
     //if(p != null) MonoBehaviour.print("Not head\n");
     xcoord = x;
     ycoord = y;
     x = x+MapGeneration3.sizeX/2;
     y = y+MapGeneration3.sizeY/2;
     if(x < 0 || y < 0 || x > MapGeneration3.sizeX-1 || y > MapGeneration3.sizeY - 1)
     {
         MonoBehaviour.print("Invalid pathfind\n");
         return;
     }
     if (blocked [x] [y])
     {
         isdead = true;
     }
     parent = p;
     tested = b;
     targetx = tx;
     targety = ty;
     b [x] [y] = true;
     blocks = blocked;
     if(tx == x && ty == y)
     {
         finalizePath (this);
     }
 }
Пример #2
0
 public void OnMapChange()
 {
     if (_targetRoom != null)
     {
         _roomPath = Astar.FindPath(_currentRoom, _targetRoom);
     }
 }
Пример #3
0
    // Setup references and default values
    void Start()
    {
        // Get ref to the parent team objects to fill out team lists
        Transform RedTeamT  = GameObject.Find("RedTeam").GetComponent <Transform>();
        Transform BlueTeamT = GameObject.Find("BlueTeam").GetComponent <Transform>();

        // Add all units to each team
        foreach (Transform child in RedTeamT)
        {
            RedTeam.Add(child.gameObject.GetComponent <Unit>());
        }
        foreach (Transform child in BlueTeamT)
        {
            BlueTeam.Add(child.gameObject.GetComponent <Unit>());
        }

        // Setting references
        layerMask      = LayerMask.GetMask("Units");
        tilemap        = GameObject.Find("GridTileMap").GetComponent <Tilemap>();
        tilemapFloor   = GameObject.Find("BackroundTileMap").GetComponent <Tilemap>(); //tile floor
        astar          = new Astar();                                                  // access to astar methods
        ActiveUnitText = GameObject.Find("ActiveUnitText").GetComponent <Text>();
        ActiveTeamText = GameObject.Find("ActiveTeamText").GetComponent <Text>();
        UnitStateText  = GameObject.Find("UnitStateText").GetComponent <Text>();
        EnergyText     = GameObject.Find("EnergyText").GetComponent <Text>();

        // Set red as first turn
        RedTeamTurn = true;
    }
Пример #4
0
    private void InitHq()
    {
        EnemyHq = Nodes.First(n => IsEnemy(n.OwnerId));
        MyHq    = Nodes.First(n => IsMe(n.OwnerId));

        Astar.CacheDist(Nodes, MyHq.Id, EnemyHq.Id);

        SilkRoad = Astar.FindPath2(Nodes, MyHq.Id, EnemyHq.Id);

        //NearestNodes = Nodes.OrderBy(n => n.DistToMyBase).ToArray();

        Player.Print($"path {SilkRoad.Count}");

        DistMapFromMe = new int[Nodes.Length];
        for (int i = 0; i < Nodes.Length; i++)
        {
            DistMapFromMe[i] = Nodes[i].DistToMyBase;
        }

        DistMapFromEnemy = new int[Nodes.Length];
        for (int i = 0; i < Nodes.Length; i++)
        {
            DistMapFromEnemy[i] = Nodes[i].DistToEnemyBase;
        }

        DistMapNone = new int[Nodes.Length];
        PathMap     = new int[Nodes.Length];
        PathPlague  = new int[Nodes.Length];
    }
Пример #5
0
    private void GoToGoal()
    {
        IEnumerable <Node> pathList = Astar.FindPath(startTilePos, endTilePos);

        pathLength = pathList.Count();
        pathIndex  = 0;
    }
Пример #6
0
        private void Start()
        {
            player          = FindObjectOfType <PlayerManager>();
            grid            = EnemyManager.Instance.grid;
            walkableTilemap = EnemyManager.Instance.walkableTilemap;
            _animator       = this.transform.GetComponentInChildren <Animator>();

            _healthBar = this.GetComponentInChildren <HealthBar>();
            _healthBar.SetBarPoints(enemyData.health, enemyData.defense);

            if (this.gameObject.GetComponentInChildren <SpriteRenderer>().gameObject.name == "EnemySprite")
            {
                spriteRenderer = this.gameObject.GetComponentInChildren <SpriteRenderer>();
            }
            else
            {
                Debug.Log("Sprite of player not found");
            }

            mainCamera = Camera.main;
            if (mainCamera)
            {
                shaker = mainCamera.GetComponent <CameraShaker>();
            }

            #region Astar Start Setup
            walkableTilemap.CompressBounds();   // réduit la taille de la tilemap à là où des tiles existent
            //roadMap.CompressBounds();
            bounds = walkableTilemap.cellBounds;
            CreateGrid();
            astar = new Astar(walkableTilesArray, bounds.size.x, bounds.size.y);
            #endregion
        }
Пример #7
0
        public override void Run()
        {
            base.Run();

            var map   = GenerateMap(45, 45);
            var astar = new Astar(map);
            var path  = astar.GetPathFromTo(map[1, 1], map[39, 31]);

            firstResult = path.Cost.ToString();

            var fiftyLocations = 0;

            // lol, this is butt ugly but a consequence of astaring it.
            var secondAstar = new Astar(map);

            for (var y = 0; y < map.GetLength(0); y++)
            {
                for (var x = 0; x < map.GetLength(1); x++)
                {
                    if (map[y, x].IsOpen)
                    {
                        var p = secondAstar.GetPathFromTo(map[1, 1], map[y, x]);
                        if (p != null && p.Cost <= 50)
                        {
                            fiftyLocations++;
                        }
                    }
                }
            }
            secondResult = fiftyLocations.ToString();

            Animate(map, path, astar);
        }
Пример #8
0
    void Start()
    {
        CreateGrid();
        astar = new Astar(grid, map.mapSize.x * 3, map.mapSize.y * 3);

        UpdateAccessibleNodesList();
    }
Пример #9
0
    private void PlaceTile(TileType tileType, int x, int y, Vector3 worldStart)
    {
        TileData tile = TileMethods.GetTile(tileType);

        if (tile.prefab)
        {
            GameObject newTile = tileDataByPool[tile].Get();
            newTile.SetActive(true);

            if (newTile)
            {
                newTile.transform.localPosition = new Vector3(worldStart.x + x * 2, 0f, worldStart.y - y * 2);

                // Astar
                Astar.AddNode(newTile.transform.localPosition, x, y, tile.walkable);
                if (tileType == TileType.Start)
                {
                    MapData.startTile.x = x;
                    MapData.startTile.y = y;
                }
                else if (tileType == TileType.End)
                {
                    MapData.endTile.x = x;
                    MapData.endTile.y = y;
                }
            }
        }
    }
Пример #10
0
    //决策移动的回合切换
    public void moveTo(int x, int y)
    {
        int[] pos = { x, y };
        astar = new Astar(row, column, pos[0], pos[1], map.GetComponent <RandomDungeonCreator>().getMap(), map.GetComponent <RandomDungeonCreator>().MapWidth, map.GetComponent <RandomDungeonCreator>().MapHeight);
        astar.isWalkableFunc = map.GetComponent <RandomDungeonCreator> ().MapWalkable;
        astar.Run();
        pathid = astar.finalpath.Count - 1;
        if (pathid >= 1)
        {
            if (map.GetComponent <RoundControler> ().CheckPlayerInBattle())
            {
                if (astar.finalpath.Count > transform.gameObject.GetComponent <playerStatus> ().MOV)
                {
                    astar.finalpath.RemoveRange(0, pathid - transform.gameObject.GetComponent <playerStatus> ().MOV);
                    pathid = astar.finalpath.Count - 1;

                    //Debug.Log ("Path long = " + astar.finalpath.Count);
                }
            }
            if (!transform.GetComponent <playerStatus>().isAI())
            {
                DrawMoveClick(astar.finalpath [0] [0], astar.finalpath [0] [1]);
            }
            //Move行为触发:决策阶段-》行动动画阶段
            Action Mov = new Action(ACTION_TYPE.ACTION_MOVE, transform.gameObject);
            Mov.MOVEPOS [0] = x;
            Mov.MOVEPOS [1] = y;
            transform.GetComponent <PhaseHandler> ().state.handle(Mov);
        }
    }
Пример #11
0
    void Start()
    {
        gm     = this;
        se     = GameObject.Find("SEManager").GetComponent <SEManager>();
        mg     = GameObject.Find("MapGenerator").GetComponent <MapGenerator>();
        player = GameObject.FindGameObjectWithTag("Player");
        //player info init
        psController = gameObject.AddComponent <PlayerStatusController>();
        psController.Set(unitPool, 2, nowFloor, hpBar, spBar, expBar, gm, LvText, skillIcon, dashIcon, attackIcon);
        //invController need psController so only use this order
        invController = gameObject.AddComponent <InventoryController>();
        invController.Set(itemPool, new List <Item>(), emptyImage, slotSprite, slotSelectSprite, inventoryUI, invenSlotGrid, itemInfo, itemName, gm, stat, InvenQuickSlot, goldText, crystalText, se);

        Astar astar = GameObject.Find("Astar").GetComponent <Astar>();

        astar.targetTile = GameObject.FindGameObjectWithTag("AstarTarget").GetComponent <Tilemap>();
        PlayerGetItem(new Item(17, 1), false);
        StartCoroutine(AutoRemoveHealthAndStamina());
        mg.gm      = this;
        mg.astar   = GameObject.Find("Astar").GetComponent <Astar>();
        mg.player  = GameObject.FindGameObjectWithTag("Player").transform;
        mg.wallcol = GameObject.Find("Wall").GetComponent <TilemapCollider2D>();
        mg.GenerateFloor();
        floortext.text = nowFloor.ToString() + "F";
    }
Пример #12
0
    private void PlaceTower()
    {
        WalkAble = false;
        if (Astar.GetPath(LevelManager.Instance.BlueSpawn, LevelManager.Instance.RedSpawn) == null)
        {
            WalkAble = true;
            return;
        }

        if (GridPosition == LevelManager.Instance.BlueSpawn || GridPosition == LevelManager.Instance.RedSpawn)
        {
            WalkAble = true;
            return;
        }

        GameObject tower = (GameObject)Instantiate(GameManager.Instance.ClickedBtn.TowerPerfab, WorldPositionTower, Quaternion.identity);

        tower.GetComponent <SpriteRenderer>().sortingOrder = GridPosition.Y;

        tower.transform.SetParent(transform);

        this.myTower = tower.transform.GetChild(0).GetComponent <Tower>();

        IsEmpty = false;
        ColorTile(Color.white);

        myTower.Price = GameManager.Instance.ClickedBtn.Price;

        GameManager.Instance.BuyTower();

        WalkAble = false;
    }
Пример #13
0
 public void moveTo(int x, int y)
 {
     int[] pos = { x, y };
     astar = new Astar(row, column, pos[0], pos[1], map.GetComponent <RandomDungeonCreator>().getMap(), 32, 32);
     astar.Run();
     //Debug.Log ("Path long = " + astar.finalpath.Count);
     pathid = astar.finalpath.Count - 1;
     if (pathid >= 1)
     {
         //				Debug.Log ("path"+pathid+":"+row + "," + column + " to " + astar.finalpath [pathid] [0] + "," + astar.finalpath [pathid] [1]);
         if (astar.finalpath [pathid] [0] < row)
         {
             moveUp();
         }
         if (astar.finalpath [pathid] [0] > row)
         {
             moveDown();
         }
         if (astar.finalpath [pathid] [1] < column)
         {
             moveLeft();
         }
         if (astar.finalpath [pathid] [1] > column)
         {
             moveRight();
         }
     }
 }
Пример #14
0
 private new void Start()
 {
     base.Start();
     weapon_GrenadeLauncher.GetComponent <SpriteRenderer>().enabled = false;
     astarPathFinder = GetComponent <Astar>();
     state           = BehaviorState.Idle;
 }
Пример #15
0
    public static List <Vector2> GetPoints(Vector2 start, Vector2 end)
    {
        for (int i = 0; i < width; ++i)
        {
            for (int j = 0; j < height; ++j)
            {
                int id = JsonTest.getMe().GetStopPoint(i, j); // [i, j];

                MapMgr.getMe().mRoadPointArr[i][j] = MapMgr.canThroughByID(id);
            }
        }


        List <APoint> _ret = Astar.SearchRoad(GetAPointByPosition(start, TILEDMAP_TYPE.START), GetAPointByPosition(end, TILEDMAP_TYPE.END), MapMgr.getMe().mRoadPointArr);


        List <Vector2> retex = new List <Vector2>();

        foreach (var data in _ret)
        {
            Vector2 pos = GetVec2ByApoint(data);
            retex.Add(pos);
        }

        return(retex);
    }
Пример #16
0
    public void Update()
    {
        /*if (player != null)
         * {
         *  if (player.position.x + weapon.range < transform.position.x)
         *      Move(4);
         *  else if (player.position.x - weapon.range > transform.position.x)
         *      Move(0);
         *  if (player.position.y + 0.1f < transform.position.y)
         *      Move(6);
         *  else if (player.position.y - 0.1f > transform.position.y)
         *      Move(2);
         * }*/

        if (Input.GetKeyDown(KeyCode.J))
        {
            List <Vector2> path = Astar.FindPath(transform.position, player.position, ref ground);

            foreach (Vector2 v in path)
            {
                Instantiate(beacon, new Vector3(v.x, v.y, 0), Quaternion.identity);
                //Debug.Log(v);
            }
        }
    }
Пример #17
0
        BezierCurvePath FindPath(Vector3 start_position, Vector3 target_position)
        {
            this.UpdateMeshFilterBounds();
            var path_list = Astar.FindPathAstar(source: start_position,
                                                destination: target_position,
                                                search_boundary: this._search_boundary,
                                                grid_granularity: this._grid_granularity,
                                                agent_size: this._actor_size,
                                                near_stopping_distance: this._approach_distance);

            if (path_list != null && path_list.Count > 0)
            {
                path_list = Astar.SimplifyPath(path: path_list, sphere_cast_radius: this._actor_size);
                path_list.Add(item: target_position);
            }
            else
            {
                path_list = new List <Vector3> {
                    start_position, target_position
                };
            }

            var path = new BezierCurvePath(start_position: start_position,
                                           target_position: target_position,
                                           game_object: this._bezier_curve,
                                           path_list: path_list);

            return(path);
        }
    public void GridUpdate()
    {
        Astar aStar = new Astar();

        pathList    = aStar.aStarBase(GridManager.Instance.grid[0, 0]);
        visitedList = aStar.getVisited();
    }
Пример #19
0
        public static void Astar()
        {
            var mapa = new MapServices();

            Console.WriteLine("Lista miast: ");
            for (int i = 0; i < mapa.AStarNodeMap.Count; i++)
            {
                Console.WriteLine(i + ". " + mapa.AStarNodeMap.ElementAt(i).Name);
            }

            int startNum, endNum;

            Console.Write("\nWybierz miasto początkowe(numer): ");
            int.TryParse(Console.ReadLine(), out startNum);

            Console.Write("Wybierz miasto końcowe(numer): ");
            int.TryParse(Console.ReadLine(), out endNum);

            AStarNode start = mapa.AStarNodeMap.ElementAt(startNum);
            AStarNode end   = mapa.AStarNodeMap.ElementAt(endNum);

            Astar             search = new Astar(end);
            IList <AStarNode> route  = search.Expand(start);

            foreach (var item in route)
            {
                Console.WriteLine(item.Name);
            }
        }
Пример #20
0
    private int GetDistance(int origin, int dest)
    {
        int[]      currentFloorTerrain = this.map.terrains[this.CurrentFloor()];
        List <int> route = Astar.Exec(origin, dest, currentFloorTerrain, this.map.width);

        return(route.Count);
    }
Пример #21
0
    private void TryWalkerWalk(int x, int y, BaseEventData data)
    {
        if (this.gameFinished)
        {
            return;
        }

        // TODO: ignore collision between camera and walker
        if (this.mainWalker.IsWalking())
        {
            return;
        }

        int destAddress = y * this.map.width + x;

        int[]      currentFloorTerrain = this.map.terrains[this.CurrentFloor()];
        List <int> route = Astar.Exec(this.mainWalker.data.address, destAddress, currentFloorTerrain, this.map.width);
        List <DirectionUtil.Direction> directions = DirectionUtil.AddressesToDirections(route, this.map.width, this.map.height);

        this.mainWalker.AppendWalkDirections(directions);

        switch (Rand.Next(10))
        {
        case 0: this.mainWalker.PlaySe(Audio.GetSE(Audio.SE.Walk1)); break;

        case 1: this.mainWalker.PlaySe(Audio.GetSE(Audio.SE.Walk2)); break;

        default: break;
        }
    }
Пример #22
0
    // Use this for initialization
    void Start()
    {
        rb2d      = GetComponent <Rigidbody2D>();
        myplanner = GetComponent <Astar>();
        myplanner.InitVars(transform.localScale.x * GetComponent <BoxCollider2D>().size.x * 0.2f);
        player = GameObject.Find("Player");

        _replan     = true;
        _follow     = false;
        _patrolling = true;
        _alert      = false;
        _lookAround = false;

        _currentPatrolPlan = 0;
        _currentAlertPlan  = 0;

        movDirection  = new Vector3(0, -1, 0);
        _patrolPoints = _myRoom.getPatrol(_roomId);

        for (int i = 0; i < _patrolPoints.Count; i++)
        {
            Debug.DrawLine(_patrolPoints[i], _patrolPoints[i] + new Vector2(0.1f, 0.1f), Color.yellow, 60f);
        }
        _patrols = InitPatrols(_patrolPoints);
    }
Пример #23
0
    private void Start()
    {
        // 获取地图数据
        PolygonCollider2D[] polygons = transform.GetComponentsInChildren <PolygonCollider2D>();
        barriersPoints = new Vector2[polygons.Length - 1][];
        for (int i = 0; i < polygons.Length; i++)
        {
            Vector2[] points = getPolygonPoints(polygons[i]);
            if (i == 0)
            {
                Debug.Log("地图多边形点数>>" + points.Length);
                mapPoints = points;
            }
            else
            {
                Debug.Log("障碍" + (i - 1) + "多边形点数>>" + points.Length);
                barriersPoints[i - 1] = points;
            }
        }

        player.localScale = Vector3.one * Astar.OFFSET;
        posBox            = new GameObject("posBox").transform;

        astar = new Astar();
    }
Пример #24
0
        private Task <Vector3Int> FindItem(Vector3Int origin, Type itemToFind)
        {
            // breadth first search for the itemtype
            HashSet <Vector3Int> failedPositions = new HashSet <Vector3Int>();
            Queue <Vector3Int>   testPositions   = new Queue <Vector3Int>();

            testPositions.Enqueue(origin);
            while (testPositions.Count > 0)
            {
                Vector3Int current = testPositions.Dequeue();
                failedPositions.Add(current);
                InventoryComponent[] inventories = ItemMap.GetInventories(current);
                foreach (InventoryComponent inventory in inventories)
                {
                    if (inventory.HasItem(itemToFind))
                    {
                        return(Task.FromResult(current));
                    }
                }

                foreach (Vector3Int delta in DeltaPositions.DeltaPositions3D)
                {
                    Vector3Int nextPos = current + delta;
                    if (Astar.IsStepValid(nextPos, current, delta) && !failedPositions.Contains(nextPos))
                    {
                        testPositions.Enqueue(nextPos);
                    }
                }
            }
            return(null);
        }
Пример #25
0
 /**
  * h函数
  */
 static float h(APoint pnt)
 {
     // return hBFS(pnt);
     return(Astar.hEuclidianDistance(pnt));
     // return hPowEuclidianDistance(pnt);
     // return hManhattanDistance(pnt);
 }
Пример #26
0
 public VehicleConfiguration()
 {
     TimerInterval         = 100;
     ForwordStep           = 5;
     Deviation             = 100;
     PathPlanningAlgorithm = new Astar();
 }
    private void computeAstar(Vector3 goalPosition)
    {
        this.goalPosition   = goalPosition;
        this.goalPosition.y = model.getVehicle().transform.position.y;         // keep closeness-to-the-goal-control in 2D

        /* compute Astar */
        pathFinder = new Astar(MyUtils.precisionAstar, MyUtils.droneRadius, false);
        if (pathFinder.setNewTargetPosition(goalPosition) == true)       //set the target for A* algorithm
        {
            pathFinder.AstarBestPathFrom(model.getVehicle().transform.position);
            path = pathFinder.getSolution();
            en   = path.GetEnumerator();
            en.MoveNext();
            isPathInProgress = true;
            //path = Chromosome.allPairPathsMatrix[CHromo,];
        }
        else
        {
            Debug.Log("Target position unreachable");
        }
        if (path == null)
        {
            Debug.Log("Astar failed!");
        }
    }
Пример #28
0
    // Setup references and default values
    void Start()
    {
        // Get ref to the parent team objects to fill out team lists
        Transform RedTeamT  = GameObject.Find("RedTeam").GetComponent <Transform>();
        Transform BlueTeamT = GameObject.Find("BlueTeam").GetComponent <Transform>();

        // Add all units to each team
        foreach (Transform child in RedTeamT)
        {
            RedTeam.Add(child.gameObject.GetComponent <Unit>());
        }
        foreach (Transform child in BlueTeamT)
        {
            BlueTeam.Add(child.gameObject.GetComponent <Unit>());
        }

        // Setting references
        layerMask      = LayerMask.GetMask("Units");
        tilemap        = GameObject.Find("GridTileMap").GetComponent <Tilemap>();
        tilemapFloor   = GameObject.Find("BackroundTileMap").GetComponent <Tilemap>(); //tile floor
        astar          = new Astar();                                                  // access to astar methods
        ActiveUnitText = GameObject.Find("ActiveUnitText").GetComponent <Text>();
        ActiveTeamText = GameObject.Find("ActiveTeamText").GetComponent <Text>();
        UnitStateText  = GameObject.Find("UnitStateText").GetComponent <Text>();
        EnergyText     = GameObject.Find("EnergyText").GetComponent <Text>();
        HPText         = GameObject.Find("HPText").GetComponent <Text>();

        // Set red as first turn
        RedTeamTurn = true;

        approachSequence = new BTSequence(new List <BTNode>
        {
            new MoveToEnemyTask(this),
        });

        attackSequence = new BTSequence(new List <BTNode>
        {
            new CheckForEnemyTask(this),
            new CheckEnemyHPTask(this),
            new AttackTask(this),
        });

        attackSafeSequence = new BTSequence(new List <BTNode>
        {
            new CheckForEnemyTask(this),
            new AttackSafeTask(this),
        });
        coverSequence = new BTSequence(new List <BTNode>
        {
            new MoveToCoverTask(this),
        });

        rootAI = new BTSelector(new List <BTNode>
        {
            approachSequence,
            attackSequence,
            attackSafeSequence,
            coverSequence,
        });
    }
Пример #29
0
    public void WorkThreadFunction(object ThreadIndex)
    {
        Debug.Log("  Thread make Over");


        astar_algorithm = new Astar();

        Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].finished_AStar = false;



        Start_Index_I = Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].Start_E_I;
        Start_Index_J = Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].Start_E_J;

        End_Index_I = Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].End_E_I;
        End_Index_J = Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].End_E_J;


        Game_Controller.Instance.indexingEnemies[(int)ThreadIndex].foundPath = astar_algorithm.FindPathActual(Game_Controller.Instance.data.rows[Start_Index_I].col[Start_Index_J],

                                                                                                              Game_Controller.Instance.data.rows[End_Index_I].col[End_Index_J]
                                                                                                              );

        //System.Threading.Thread.Sleep(2000);
        Game_Controller.Instance.indexingEnemies [(int)ThreadIndex].finished_AStar = true;

        Debug.Log("  Thread make Over end");
    }
Пример #30
0
    // Use this for initialization

    void Start()
    {
        step  = stepObj.GetComponent <Step>();
        point = new Vector3(7, 2);

        ph = new PathController(gameObject);

        gameObject.transform.GetComponentInParent <CheckPath>().OnTriggerObjects += delegate()
        {
            Vector2 pos;
            IEnumerable <GameObject> boots;

            ph.GetOverlap(out pos, out boots);

            ph.GetValue(boots, pos);
        };

        //При поступлении шага
        step.StepDone += delegate()
        {
            CheckPath.stop = false;

            Astar star = new Astar(transform.position, point);
            path = star.GetPath();

            gameObject.GetComponent <Path>().path = path;
        };
    }
Пример #31
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        Astar astar = (Astar)target;

        GUILayout.Label("Choose a Heuristic", EditorStyles.boldLabel);
        if (GUILayout.Button("Null Heuristic"))
        {
            astar.chosenHeuristic = 0;
        }
        if (GUILayout.Button("Euclidean Distance Heuristic"))
        {
            astar.chosenHeuristic = 1;
        }
        if (GUILayout.Button("Clustering Heuristic"))
        {
            astar.chosenHeuristic = 2;
        }

        GUILayout.Label("Running Time", EditorStyles.boldLabel);
        if (!astar.GridPathfinding && GUILayout.Button("Activate Grid Pathfinding"))
        {
            astar.GridPathfinding = true;
        }
        if (!astar.GraphPathfinding && GUILayout.Button("Activate Graph Pathfinding"))
        {
            astar.GraphPathfinding = true;
        }
    }
Пример #32
0
 public void Pathfind(int x, int y)
 {
     bool[][] testedGrid = new bool[MapGeneration3.sizeX][];
     for(int i = 0; i < MapGeneration3.sizeX; i++)
     {
         testedGrid[i] = new bool[MapGeneration3.sizeY];
     }
     head = (Astar)ScriptableObject.CreateInstance("Astar");
     head.Astarinit(null, (int)transform.position.x, (int)transform.position.y, testedGrid, x, y, MapGeneration3.occupiedGrid);
     //head = new Astar (null, (int)transform.position.x, (int)transform.position.y, testedGrid, x, y, MapGeneration3.occupiedGrid);
     int patience;
     for(patience = 1000; !(head.isFinal ()) && patience > 0; patience--)
     {
         head.extend();
     }
     //print ("Found at patience = " + patience);
     if(patience == 0) m.found = true;
     testedGrid = null;
 }
Пример #33
0
    int[,] whichList; //2 dimensional array used to record

    #endregion Fields

    #region Constructors

    //-----------------------------------------------------------------------------
    // Name: AstarLibrary
    // Desc: Initializes/Redimensionates all required vars and generates walkability map.
    //-----------------------------------------------------------------------------
    public Astar(Cell[,] arr)
    {
        instance = this;

        //get map dimensions
        mapWidth = arr.GetLength(0);
        mapHeight = arr.Length / arr.GetLength(0);
        //Redimensionate needed arrays
        openList = new int[mapWidth * mapHeight + 2]; //1 dimensional array holding ID# of open list items
        whichList = new int[mapWidth + 1, mapHeight + 1];  //2 dimensional array used to record
        //whether a cell is on the open list or on the closed list.
        openX = new int[mapWidth * mapHeight + 2]; //1d array stores the x location of an item on the open list
        openY = new int[mapWidth * mapHeight + 2]; //1d array stores the y location of an item on the open list
        parentX = new int[mapWidth + 1, mapHeight + 1]; //2d array to store parent of each cell (x)
        parentY = new int[mapWidth + 1, mapHeight + 1]; //2d array to store parent of each cell (y)
        Fcost = new int[mapWidth * mapHeight + 2];	//1d array to store F cost of a cell on the open list
        Gcost = new int[mapWidth + 1, mapHeight + 1]; 	//2d array to store G cost for each cell.
        Hcost = new int[mapWidth * mapHeight + 2];	//1d array to store H cost of a cell on the open list

        // walkability array:
        // is a bidimensional int-array of ones and zeros that we generate from cells walkable states.

        // TODO: Would be nice to be able to get walkability at real time from a given external function,
        //       Right now, we have to refresh astar walkability from external grid

        walkability = new int[mapWidth, mapHeight];
        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {
                if (arr[x, y].walkable) {
                    walkability[x, y] = walkable;
                } else {
                    walkability[x, y] = unwalkable;
                }
            }
        }
    }
Пример #34
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures:
            spriteBatch = new SpriteBatch(GraphicsDevice);

            /*	LOAD THE FONT:	*/
            font = Content.Load<SpriteFont>(@"8bit_font");

            /*	CREATE GRID:	*/
            grid = new Sprite(Content.Load<Texture2D>("iso_grid_spooky"), 0, 0, 64, 64, 1, false);
            grid.set_pos_x(0);
            grid.set_pos_y(0);

            /*	CREATE OBSTACLE:	*/
            obstacle = new Sprite(Content.Load<Texture2D>("iso_obstacle_spooky_box_closed"), 0, 0, 64, 96, 1, false);
            obstacle.set_pos_x(0);
            obstacle.set_pos_y(0);

            /*	CREATE OBSTACLE BLUEPRINT:	*/
            obstacle_blueprint = new Sprite(Content.Load<Texture2D>("iso_obstacle_spooky_box_closed_blueprint"), 0, 0, 64, 96, 1, false);
            obstacle_blueprint.set_pos_x(0);
            obstacle_blueprint.set_pos_y(0);

            /*	CREATE GHOST:	*/
            ghost = new Unit();
            //ghost.movement_speed_x = -1;
            //ghost.movement_speed_y = 1;
            ghost.calc_pos_px(0, 0, TILE_WIDTH, TILE_HEIGHT);
            ghost.route.start = new Node(ghost.pos.PosXMatrix, ghost.pos.PosYMatrix);
            ghost.route.finish = new Node(15, 14);
            Astar astarGhost = new Astar(ghost.route, _gamemap);
            ThreadStart TAstar = new ThreadStart(astarGhost.find_path);
            Thread thread = new Thread(TAstar);
            thread.Start();
            //pathfinder.find_path(ghost.route, gamemap);
            if (ghost.route.routeActive)
            {
                ghost.calc_dest_pos_px(ghost.route.Steps[0].pos_x, ghost.route.Steps[0].pos_y, TILE_WIDTH, TILE_HEIGHT);
                ghost.route.Steps.RemoveAt(0);
            }
            //ghost.pos.calc_pos_matrix(0, 512, TILE_WIDTH, TILE_HEIGHT);
            ghost.Texture = new Sprite(Content.Load<Texture2D>("ghost_2"), 0, 0, 64, 64, 6, true);

            /*	CREATE HIGHLIGHTED GRID:	*/
            highlighted_grid = new Sprite(Content.Load<Texture2D>("iso_highlighted_grid"), 0, 0, 64, 32, 0, false);
            highlighted_grid.set_pos_x(0);
            highlighted_grid.set_pos_y(0);

            _sfxBuildObstacle = Content.Load<SoundEffect>("build_obstacle");

            /*	INIT THE LIST:	*/
            _theList = new TileList( _gamemap, ghost );
        }
Пример #35
0
 public Astar popNext()
 {
     head = head.getNext ();
     return head;
 }
Пример #36
0
    void Start()
    {
        Map = new AstarMap(10,10);

        for (int i = 0; i < Nodes.GetLength(0); i++) {

            for (int j = 0; j < Nodes.GetLength(1); j++) {

                if (Nodes[i, j] == 1) {

                    Map.RegisterWalkability(new Vector2(i, j), false);

                    GameObject colon = Instantiate(Blocker) as GameObject;
                    colon.transform.SetParent(transform);
                    colon.transform.localPosition = Grid2World(Map.GetNode(i,j).Position);

                }
            }

        }

        Astar = new Astar(Map);

        CreatePlayer();
    }
Пример #37
0
 /// <summary>
 /// Finalizes the path.
 /// </summary>
 /// <param name="n">A reference to the Astar object to be set as the next point in the path</param>
 void finalizePath(Astar n)
 {
     //MonoBehaviour.print("finalizing\n");
     next = n;
     isrealpath = true;
     tested [xcoord+MapGeneration3.sizeX/2] [ycoord+MapGeneration3.sizeY/2] = false;
     if(parent != null)
     {
         parent.finalizePath (this);
     }
 }