Inheritance: MonoBehaviour
Beispiel #1
0
        /* The keeper will move to a new position depending on the ball's position and direction. */
        public override PlayerAction ActionWithoutBall(Player player, GameAction gameAction)
        {
            Pathfinding pathfinding = new Pathfinding();
            Point ballTarget = GameAI.BallNextRoundLocation();
            bool onOwnSide = GameAI.IsPointOnOwnSide(GameAI.PlayersTeam(player), ballTarget);
            if (onOwnSide)
            {
                if (GameAI.GameBall.IsInShootState)
                {
                    Point ballTargetGridLocation = pathfinding.GetGridLocation(GameAI.GameBall.ExactTargetLocation);

                    Goal ownGoal = GameAI.PlayersTeam(player).TeamGoal;

                    Point? pointBeforeGoalEntry = GameAI.PointBeforeRectangleEntry(ownGoal.GoalRectangle);

                    //true if the ball will go through the goal
                    if (pointBeforeGoalEntry.HasValue)
                    {
                        return GoalKeeperShootDefense(player, pointBeforeGoalEntry.Value);
                    }
                }
                else
                {
                    return GoalKeeperPassDefense(player, ballTarget);
                }
            }

            return null;
        }
    // Use this for initialization
    void Start()
    {
        graph = new Pathfinding();
        graph.Load("PathfindingRodrigueTest");
        graph.setNeighbors();

        target = GameObject.FindGameObjectWithTag("Target");
        road = PathfindingManager.GetInstance().GetRoad(transform.position, target.transform.position, graph);
        road = PathfindingManager.GetInstance().SmoothRoad(road);

        canShoot = true;
        //targetPossible = GameObject.FindGameObjectsWithTag("Target");
        //foreach (GameObject temp in targetPossible)
        //{
        //    if (temp != this.gameObject)
        //    {
        //        //if(temp.transform.parent.GetComponent<TeamNumber>().teamName != "RektByRodrigue")
        //        //{
        //        listOfTarget.Add(temp);
        //        //}
        //    }
        //}
        ////InvokeRepeating("GetTarget", 0.5f, 0.5f);
        //currentTarget = targetPossible[0];
        spawnPoint = transform.position;
        rateOfFire = 1;
        //InvokeRepeating("FindTarget", 0.1f, 0.1f);
        InvokeRepeating("UpdateRoad", 0.5f, 0.5f);
    }
Beispiel #3
0
 void CompletePath(Pathfinding.Path p)
 {
     if (!p.error) {
         path = p;
         currentWayPoint = 1;
         if (p.vectorPath.Count == 1) currentWayPoint = 0;
         if (!animator.GetBool("Running")) animator.SetBool("Run",true);
     }
 }
 public JordanMoveTask()
 {
     //Select your pathfinding
     graph = new Pathfinding();
     graph.Load("Windywyll");
     graph.setNeighbors();
     delayTimerUpdateRoad = 1.0f;
     startTimerUpdateRoad = Time.time;
 }
Beispiel #5
0
        public override PlayerAction CornerDefense(Player player)
        {
            Pathfinding pathfinding = new Pathfinding();

            Point targetPoint = player.StartLocation;
            targetPoint.X = GameAI.PlayersTeam(player).TeamGoal.MiddlePoint.X + pathfinding.CalculateHorizontalDirection(GameAI.PlayersTeam(player).TeamGoal.MiddlePoint, new Point(12, 12)) * 7;

            return new PlayerAction(null, targetPoint, ActionType.Run);
        }
        private static void drawText(SpriteBatch spriteBatch, int tileSize, int px, int py, Pathfinding.Node node)
        {
            String heuristic = (Math.Truncate(node.h * 10) / 10).ToString();
              String moveValue = (Math.Truncate(node.g * 10) / 10).ToString();
              String totalValue = (Math.Truncate(node.f * 10) / 10).ToString();
              spriteBatch.DrawString(Game1.font, heuristic, new Vector2(px + tileSize - 20, py), Color.White);
              spriteBatch.DrawString(Game1.font, moveValue, new Vector2(px, py), Color.White);

              if (node.f != Pathfinding.Map.INFINITY)
            spriteBatch.DrawString(Game1.font, totalValue.ToString(), new Vector2(px + tileSize / 2, py + tileSize / 2), Color.White);
        }
    // Use this for initialization
    void Start()
    {
        //Select your pathfinding
        graph = new Pathfinding();
        graph.Load("BenoitV");
        graph.setNeighbors();
        //

        road = PathfindingManager.GetInstance().GetRoad(transform.position, target.transform.position,graph);
        InvokeRepeating("UpdateRoad", 0.5f,1f);
        Debug.Log(PathfindingManager.GetInstance().test);
    }
Beispiel #8
0
    // Use this for initialization
    void Start()
    {
        //Select your pathfinding
        graph = new Pathfinding();
        graph.Load("PoulpeNavMesh");
        graph.setNeighbors();
        //

        target = GameObject.FindGameObjectWithTag("Target");
        road = PathfindingManager.GetInstance().GetRoad(transform.position, target.transform.position,graph);
        InvokeRepeating("UpdateRoad", 0.5f, 0.5f);
        Debug.Log(PathfindingManager.GetInstance().test);
    }
    public SW_Walk(int id, float pSpeed, float pRange, string graphName)
        : base(id)
    {
        target = TeamManagerWill.instance.mainTarget;
        closeEnoughRange = pRange;
        speed = pSpeed;
        graph = new Pathfinding();
        graph.Load(graphName);
        graph.setNeighbors();

        player = TeamManagerWill.instance.members[idAgent].gameObject;
        playerController = player.GetComponent<CharacterController>();
        road = PathfindingManager.GetInstance().GetRoad(player.transform.position, target.transform.position, graph);
        road = PathfindingManager.GetInstance().SmoothRoad(road);
    }
 /* Returns a list with all players who will tackle in this round. */
 public List<Player> SearchTacklePlayers(Player[] allPlayers)
 {
     List<Player> tacklePlayers = new List<Player>();
     foreach (Player player in allPlayers)
     {
         ActionType type;
         Pathfinding pathfinding = new Pathfinding();
         //returns the last action type which the player will execute in this round.
         pathfinding.PlayerAtSpecificRound(player, 1, out type);
         if (type == ActionType.Tackle)
         {
             tacklePlayers.Add(player);
         }
     }
     return tacklePlayers;
 }
    // Use this for initialization
    void Start()
    {
        //Select your pathfinding
        graph = new Pathfinding();
        graph.Load("Windywyll");
        graph.setNeighbors();
        //

        GameObject[] temp = GameObject.FindGameObjectsWithTag("Target");
        enemies = new List<GameObject>(temp);
        enemies.Remove(gameObject);

        target = enemies[Random.Range(0, enemies.Count)];
        road = PathfindingManager.GetInstance().GetRoad(transform.position, target.transform.position, graph);
        InvokeRepeating("UpdateRoad", 0.5f, 0.5f);
        Debug.Log(PathfindingManager.GetInstance().test);
    }
Beispiel #12
0
        /// <summary>
        /// For the case that the enemy has the ball and is close to the own goal.
        /// </summary>
        /// <param name="player">The player who will execute the action</param>
        /// <returns></returns>
        public virtual PlayerAction ActionEnemyClose(Player player)
        {
            Pathfinding pathfinding = new Pathfinding();
            Team enemyTeam = GameAI.GetEnemyTeam(GameAI.PlayersTeam(player));
            ActionType type;

            List<Player> nearPlayersToPenaltyPoint = GameAI.NearestPlayersToPoint(enemyTeam, GameAI.PenaltyKickPoint(enemyTeam.TeamGoal), 2, 1, false);

            Player nearPlayer;
            if (nearPlayersToPenaltyPoint.ElementAt(0).Equals(player))
            {
                nearPlayer = nearPlayersToPenaltyPoint.ElementAt(1);
            }
            else
            {
                nearPlayer = nearPlayersToPenaltyPoint.ElementAt(0);
            }
            Point nextPlayerLocation = pathfinding.PlayerAtSpecificRound(nearPlayer, 1, out type);

            return new PlayerAction(null, nextPlayerLocation, ActionType.Run);
        }
Beispiel #13
0
    public static void ShowRecastNavmesh(DbgRenderMesh renderMesh, PolyMeshAsset.PolyMeshData pmesh, Pathfinding.Config config)
    {

        renderMesh.Clear();

        UnityEngine.Random.seed = c_RandomSeed;

        int npolys = pmesh.npolys;
        int nvp = pmesh.nvp;
        int[] tri = new int[3];
        Vector3[] verts = new Vector3[3];
        for (int i = 0; i < npolys; ++i)
        {
            int pIndex = i * nvp * 2;
            Color col = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value);
            for (int j = 2; j < nvp; ++j)
            {
                if (pmesh.polys[pIndex + j] == RC_MESH_NULL_IDX)
                    break;
                tri[0] = pmesh.polys[pIndex];
                tri[1] = pmesh.polys[pIndex + j - 1];
                tri[2] = pmesh.polys[pIndex + j];

                for (int k = 0; k < 3; ++k)
                {
                    int vIndex = tri[k] * 3;
                    verts[k].x = config.bmin[0] + pmesh.verts[vIndex + 0] * pmesh.cs;
                    verts[k].y = config.bmin[1] + (pmesh.verts[vIndex + 1] + 1) * pmesh.ch + 0.1f;
                    verts[k].z = config.bmin[2] + pmesh.verts[vIndex + 2] * pmesh.cs;
                }
                col = VaryColor(col);
                renderMesh.AddTriangle(new DbgRenderTriangle(verts[0], verts[1], verts[2], col));
            }
        }
        renderMesh.Rebuild();
    }
Beispiel #14
0
 // Start is called before the first frame update
 void Start()
 {
     pathFinding = new Pathfinding(10, 10, 1, Vector3.zero);
 }
Beispiel #15
0
 protected new void Awake()
 {
     base.Awake();
     sm = GameObject.FindWithTag("MainCamera").GetComponent<StateMachine>();
     nametag = gameObject.AddComponent<Nametag>();
     pathfinding = gameObject.AddComponent<Pathfinding>();
     d20 = gameObject.AddComponent<D20>();
 }
Beispiel #16
0
    public IEnumerator EnemyMove(int rows, int columns, List <Vector3> currentUnwalkables)
    {
        UnitState priorState = state;

        state = UnitState.BUSY;

        if (dead || stun)
        {
            state = priorState;
            yield break;
        }

        targets = GameObject.FindGameObjectsWithTag("Player");

        int             temp     = int.MaxValue;
        List <PathNode> tempPath = new List <PathNode>();

        foreach (GameObject t in targets)
        {
            /*if (t.GetComponent<MovingObject>().health < tHealth)
             * {
             *  tHealth = t.GetComponent<MovingObject>().health;
             *  target = t.transform;
             *
             *  currentUnwalkables.Remove(target.position);
             *
             *  currentUnwalkables.Remove(transform.position);
             *
             *  pathfinding = new Pathfinding(columns, rows, currentUnwalkables);
             *
             *  path = pathfinding.FindPath((int)transform.position.x, (int)transform.position.y, (int)target.position.x, (int)target.position.y);
             * }*/

            currentUnwalkables.Remove(t.transform.position);

            currentUnwalkables.Remove(transform.position);

            pathfinding = new Pathfinding(columns, rows, currentUnwalkables);

            path = pathfinding.FindPath((int)transform.position.x, (int)transform.position.y, (int)t.transform.position.x, (int)t.transform.position.y);

            if (path != null && path.Count < temp)
            {
                temp     = path.Count;
                tempPath = path;
                target   = t.transform;
            }
            else
            {
                path = tempPath;
            }

            currentUnwalkables.Add(t.transform.position);
        }

        if (path == null)
        {
            Debug.Log("No possible routes to targets!");
            yield break;
        }

        if (path.Count == 0)
        {
            ChangeFacingDirection(target.position - transform.position);
            if (ReadyAbility(0))
            {
                yield return(new WaitForSeconds(.5f));

                CastAbility();
            }
            yield return(null);
        }
        else
        {
            for (int i = 0; energy > 0 && i < path.Count; i++)
            {
                facingDirection = path[i].coord - transform.position;
                ChangeFacingDirection(facingDirection);
                yield return(StartCoroutine(Move((int)facingDirection.x, (int)facingDirection.y)));

                if (health <= 0 || stun)
                {
                    state = priorState;
                    yield break;
                }

                //yield return new WaitForSeconds(.1f);

                if (Vector3.Distance(transform.position, target.position) <= 1)
                {
                    ChangeFacingDirection(target.position - transform.position);
                    if (ReadyAbility(0))
                    {
                        yield return(new WaitForSeconds(.5f));

                        CastAbility();
                    }
                }
            }
        }
        state  = priorState;
        target = null;
    }
Beispiel #17
0
 private void Start()
 {
     this.pathfinding = new Pathfinding(10, 10);
     Instantiate(pacmanPrefab);
 }
Beispiel #18
0
    private static void calcTightTileBounds(Pathfinding.TileCacheLayerHeader header, ref float[] bmin, ref float[] bmax, float cs)
    {
        bmin[0] = header.bmin[0] + header.minx* cs;
        bmin[1] = header.bmin[1];
	    bmin[2] = header.bmin[2] + header.miny* cs;
        bmax[0] = header.bmin[0] + (header.maxx+1)*cs;
	    bmax[1] = header.bmax[1];
	    bmax[2] = header.bmin[2] + (header.maxy+1)*cs;
    }
 void Awake()
 {
     instance    = this;
     pathfinding = GetComponent <Pathfinding>();
 }
 private void Awake()
 {
     pf = GameObject.Find("GameManager").GetComponent <Pathfinding>();
 }
Beispiel #21
0
 void Awake()
 {
     pathfinding = GameObject.Find("BattleManager").GetComponent<Pathfinding>();
 }
 private void Awake()
 {
     pathfinding = GetComponent <Pathfinding>();
 }
Beispiel #23
0
        public override bool Update(int tick)
        {
            if (tasks != null)
            {
                if (tasks.First().TaskComplete(this))
                {
                    tasks.RemoveAt(0);
                    if (currentPath != null && isEnd(this))
                    {
                        this.rack.Move(this.x + 1000, this.y, this.z);
                        this.rack = null;

                        this.Move(this.x, this.y, this.z + 90);
                        currentPath = Pathfinding.Listnodes(currentNode, "Y" + this._name, Pathfinding.listOfNodes, this.path);
                        this.AddTask(new TruckMove(currentPath));
                    }

                    if (tasks.Count == 0)
                    {
                        tasks = null;
                    }
                    else
                    {
                        tasks.First().StartTask(this);
                    }
                }
            }
            if (this.rack != null)
            {
                this.rack.Move(this.x, this.y + 1, this.z + 1.5);
                if (tasks == null)
                {
                    currentPath.Clear();
                    this.currentPath = Pathfinding.Listnodes(currentNode, "Z" + this._name, Pathfinding.listOfNodes, this.path);
                    tasks            = new List <ITruckTask>();
                    this.AddTask(new TruckMove(this.currentPath));
                }
            }
            if (this.currentPath != null && this.currentPath.Count != 0)
            {
                this._x = Math.Round(this._x, 1);
                this._z = Math.Round(this._z, 1);

                if (this._x < currentPath[0].GetX())
                {
                    this.Move(this.x + 0.1, this.y, this.z);
                }
                else if (this._x > currentPath[0].GetX())
                {
                    this.Move(this.x - 0.1, this.y, this.z);
                }
                else if (this._z < currentPath[0].GetZ())
                {
                    this.Move(this.x, this.y, this.z + 0.1);
                }
                else if (this._z > currentPath[0].GetZ())
                {
                    this.Move(this.x, this.y, this.z - 0.1);
                }
                else
                {
                    this.currentNode = currentPath[0].GetName();
                    currentPath.RemoveAt(0);
                }
            }
            return(base.Update(tick));
        }
Beispiel #24
0
    void GenerateBoard()
    {
        GameObject go = Resources.Load <GameObject>(FilePath.TilePrefab);
        SavedDatabase <TileTypes> tileDB = Globals.campaign.GetTileData().Tiles;

        int sizeX = currMap.sizeX;
        int sizeY = currMap.sizeY;

        pathfinding = new Pathfinding(sizeX, sizeY);
        EffectBoard = new TileEffectSprite[sizeX, sizeY];

        for (int x = 0; x < sizeX; x++)
        {
            for (int y = 0; y < sizeY; y++)
            {
                //Heres where we'll probably adjust the height map stuff

                GameObject temp = Instantiate(go, transform);
                TileData   data = new TileData(x, y);

                // maybe we should create a new board that will just replace the board in the current
                // map?
                TileTypes types = tileDB.GetCopy(currMap.tileBoard[x, y]);
                //currMap.tileBoard[x, y] = types;

                Tile newTile = temp.GetComponent <Tile>();
                temp.GetComponent <Tile>().InitTile(data, types);

                pathfinding.AddTile(newTile, x, y);

                // temp.transform.position = Globals.HeightCorrectedPosition(pathfinding.tiles[x, y]);
                temp.transform.position = Globals.GridToWorld(x, y);

                temp.GetComponent <SpriteRenderer>().sprite = atlas.GetSprite(types.spriteFilePath);
                temp.name = x + " " + y;

                // we create a concection between the tile effects on the map and the
            }
        }

        if (currentMission.started == false)
        {
            foreach (Tuple <MapCoords, List <string> > key in currentMission.initTileEffects)
            {
                int x = key.ele1.X;
                int y = key.ele1.Y;

                List <TileEffect> effects = new List <TileEffect>();

                foreach (string s in key.ele2)
                {
                    effects.Add(Globals.campaign.GetTileData().Effects.GetCopy(s));
                }

                pathfinding.tiles[x, y].tileEffects = effects;
                pathfinding.tiles[x, y].InitTileEffect();
                pathfinding.tiles[x, y].InitTileEffectsVisuals();
                pathfinding.tiles[x, y].ProcessEffectQueue();
            }
        }

        pathfinding.PopulateNieghbors();
    }
Beispiel #25
0
 public Pathfinding(int width, int height, float cellSize, Vector3 position)
 {
     Instance = this;
     grid     = new CustomGrid <PathNode>(width, height, cellSize, position, (CustomGrid <PathNode> g, int x, int z) => new PathNode(g, x, z), true);
 }
Beispiel #26
0
 void Awake()
 {
     instance = this;
     grid     = GetComponent <Grid>();
 }
	public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
		Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(script.astarData, settings);
		sr.OpenSerialize();
		script.astarData.SerializeGraphsPart (sr);
		sr.SerializeEditorSettings (graphEditors);
		byte[] bytes = sr.CloseSerialize();
		checksum = sr.GetChecksum ();
		return bytes;
		
		//Forward to runtime serializer
		//return script.astarData.SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings, out checksum);
	}
Beispiel #28
0
 private void Awake()
 {
     instance         = this;
     pathfinding      = GetComponent <Pathfinding>();
     pathRequestQueue = new Queue <PathRequest>();
 }
	public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
		byte[] bytes = null;
		uint ch = 0;
		AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (delegate (bool force) {
			Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(script.astarData, settings);
			sr.OpenSerialize();
			script.astarData.SerializeGraphsPart (sr);
			sr.SerializeEditorSettings (graphEditors);
			bytes = sr.CloseSerialize();
			ch = sr.GetChecksum ();
	#if ASTARDEBUG
			Debug.Log ("Got a whole bunch of data, "+bytes.Length+" bytes");
	#endif
			return true;
		}));
		
		//Make sure the above work item is run directly
		AstarPath.active.FlushWorkItems();
		checksum = ch;
		return bytes;
		
		//Forward to runtime serializer
		//return script.astarData.SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings, out checksum);
	}
 public Pathfinding(int width, int height, Vector3 origin)
 {
     Instance    = this;
     grid        = new Grid <PathNode>(width, height, 1f, origin, (Grid <PathNode> g, int x, int y) => new PathNode(g, x, y));
     this.origin = origin;
 }
    // Use this for initialization
    void Start()
    {
        //theStateMachine = new StateMachineAntoine(gameObject);

        graph = new Pathfinding();
        graph.Load("antoinePathFinding");
        graph.setNeighbors();

        SpawnPos = transform.position;

        //int rand = Random.Range(0, nodes.transform.childCount - 1);

        //target = nodes.transform.GetChild(rand).gameObject;

        //PathPoint = points[index].transform.position;

        enemies = GameObject.FindGameObjectsWithTag("Target");

        for (int i = 0; i < enemies.Length; i++)
        {
            if (enemies[i] == gameObject)
            {
                enemies[i] = null;
            }
            else if (enemies[i] == bro1)
            {
                enemies[i] = null;
            }
            else if (enemies[i] == bro2)
            {
                enemies[i] = null;
            }
        }

        InvokeRepeating("ChangeColor", 0.5f, 0.1f);

        InvokeRepeating("FindNewTarget", 0f, 0.5f);

        InvokeRepeating("Calc", 0f, 1.0f);

        isMoving = false;
        isShooting = false;
        canShoot = true;
        bullet = Resources.Load("Bullet") as GameObject;
        finished = false;

        decisionTree = new SelectorAntoine();
        SequenceAntoine s1 = new SequenceAntoine();
        FiltreAntoine f1 = new FiltreAntoine(DelegateInvertBool);
        TaskAntoineDelegate delegateSeePlayer = new TaskAntoineDelegate(HaveTarget);
        SelectorAntoine se1 = new SelectorAntoine();
        SequenceAntoine s2 = new SequenceAntoine();
        TaskAntoineDelegate delegateCanShoot = new TaskAntoineDelegate(GetCanShootDelegate);
        TaskAntoineDelegate delegateShootBullet = new TaskAntoineDelegate(ShootBullet);
        TaskAntoineDelegate delegateDodge = new TaskAntoineDelegate(DelegateDodge);
        SelectorAntoine se2 = new SelectorAntoine();
        SequenceAntoine s4 = new SequenceAntoine();
        TaskAntoineDelegate delegateDistance = new TaskAntoineDelegate(DelegateDistance);
        TaskAntoineDelegate delegateChase = new TaskAntoineDelegate(DelegateChase);
        TaskAntoineDelegate delegatePatrol = new TaskAntoineDelegate(DelegatePatrol);

        decisionTree.AddNode(s1);
        decisionTree.AddNode(se2);

        //s1.AddNode(f1);
        s1.AddNode(delegateSeePlayer);
        s1.AddNode(se1);

        // f1.AddNode(delegateSeePlayer);

        se1.AddNode(s2);
        se1.AddNode(delegateDodge);

        s2.AddNode(delegateCanShoot);
        s2.AddNode(delegateShootBullet);

        se2.AddNode(s4);
        se2.AddNode(delegatePatrol);

        s4.AddNode(delegateDistance);
        s4.AddNode(delegateChase);
    }
Beispiel #32
0
 public Pathfinding(int width, int height, float CellSize, Vector3 originPosition)
 {
     Instance = this;
     Grid     = new Grid <PathNode>(width, height, CellSize, originPosition, (Grid <PathNode> g, int x, int y) => new PathNode(g, x, y));
 }
Beispiel #33
0
 // Start is called before the first frame update
 void Start()
 {
     pathfinding = new Pathfinding(20, 20);
 }
Beispiel #34
0
 private void Start()
 {
     pathfinding = FindObjectOfType <Pathfinding>();
 }
Beispiel #35
0
 private void Awake()
 {
     pathfinding = GameObject.FindGameObjectWithTag("Navigation").GetComponent <Pathfinding>();
 }
Beispiel #36
0
 void Awake()
 {
     base.Awake();
     pathfinding = GetComponent <Pathfinding>();
 }
Beispiel #37
0
 //Constructor
 public Pathfinding(int width, int height, Vector3 originPosition, LayerMask[] unwalkableMasks, float walkableCheckRadius, bool showDebug)
 {
     Instance = this;
     grid     = new GridSystem <PathNode>(width, height, 1, originPosition, (GridSystem <PathNode> grid, int x, int y) => new PathNode(grid, x, y, originPosition, unwalkableMasks), showDebug);
     this.walkableCheckRadius = walkableCheckRadius;
 }
Beispiel #38
0
        public bool RunAround(IAbilityUnit unit, Vector3 target)
        {
            if (this.Unit.SourceUnit.MovementSpeed <= unit.SourceUnit.MovementSpeed)
            {
                return(false);
            }

            var unitPosition   = this.Unit.Position.PredictedByLatency;
            var targetPosition = unit.Position.PredictedByLatency;

            if (target.Distance2D(targetPosition) < 200)
            {
                this.Unit.SourceUnit.Move(unit.SourceUnit.InFront(250));
                return(true);
            }

            if (this.Unit.Position.PredictedByLatency.Distance2D(target)
                < unit.Position.PredictedByLatency.Distance2D(target) ||
                this.Unit.Position.PredictedByLatency.Distance2D(unit.Position.PredictedByLatency) > 250)
            {
                return(false);
            }

            var infront = unit.SourceUnit.InFront(500);

            // infront =
            // this.Target.SourceUnit.InFront(
            // (this.Unit.Position.Current.Distance2D(infront) / this.Unit.SourceUnit.MovementSpeed)
            // * this.Target.SourceUnit.MovementSpeed);
            var backWardsdirection = (targetPosition - infront).Normalized();
            var projectionInfo     = Vector3Extensions.ProjectOn(targetPosition, unitPosition, infront);
            var projectionInfo2    = Vector3Extensions.ProjectOn(
                unitPosition,
                targetPosition + backWardsdirection * (unitPosition.Distance2D(targetPosition) + 200),
                infront);
            var isCloserToFront = unitPosition.Distance2D(infront) + this.Unit.SourceUnit.HullRadius
                                  + unit.SourceUnit.HullRadius + 100 < targetPosition.Distance2D(infront);
            var distanceFromSegment2 = unitPosition.Distance2D(
                Vector2Extensions.ToVector3(projectionInfo2.SegmentPoint));
            var canBlock = (projectionInfo2.IsOnSegment || distanceFromSegment2 < unit.SourceUnit.HullRadius / 2) &&
                           isCloserToFront;

            if (!canBlock &&
                (projectionInfo.IsOnSegment ||
                 targetPosition.Distance2D(Vector2Extensions.ToVector3(projectionInfo.SegmentPoint))
                 < unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 20))
            {
                var direction  = (infront - targetPosition).Normalized();
                var direction1 = (infront - targetPosition).Perpendicular().Normalized();
                var direction2 = (targetPosition - infront).Perpendicular().Normalized();

                // Console.WriteLine(direction1 + " " + direction2);
                var position = Pathfinding.ExtendUntilWall(
                    targetPosition,
                    direction1,
                    Math.Max(unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100, distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var position2 = Pathfinding.ExtendUntilWall(
                    targetPosition,
                    direction2,
                    Math.Max(unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100, distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var distance  = unitPosition.Distance2D(position);
                var distance2 = unitPosition.Distance2D(position2);
                if (distance2 < distance)
                {
                    distance = distance2;
                    position = position2;
                }

                if (!isCloserToFront)
                {
                    if (distanceFromSegment2 < unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 50)
                    {
                        infront = Pathfinding.ExtendUntilWall(position, direction, distance + 500, this.Unit.Pathfinder.EnsagePathfinding);
                    }
                    else
                    {
                        infront = Pathfinding.ExtendUntilWall(unitPosition, direction, 500, this.Unit.Pathfinder.EnsagePathfinding);
                    }
                }

                // else
                // {
                // infront = Pathfinding.ExtendUntilWall(unitPosition, direction, 300, this.Pathfinder);
                // }
            }
            else
            {
                return(false);
            }

            this.Unit.SourceUnit.Move(infront);
            return(true);
        }
Beispiel #39
0
    public byte[] SerializeGraphs(Pathfinding.Serialization.SerializeSettings settings, out uint checksum)
    {
        Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(script.astarData, settings);
        sr.OpenSerialize();
        script.astarData.SerializeGraphsPart (sr);
        sr.SerializeEditorSettings (graphEditors);
        byte[] bytes = sr.CloseSerialize();
        checksum = sr.GetChecksum ();
        #if ASTARDEBUG
        Debug.Log ("Got a whole bunch of data, "+bytes.Length+" bytes");
        #endif
        return bytes;

        //Forward to runtime serializer
        //return script.astarData.SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings, out checksum);
    }
	public static void SetTagField (GUIContent label, ref Pathfinding.TagMask value) {
		
		GUILayout.BeginHorizontal ();
		
		//Debug.Log (value.ToString ());
		EditorGUIUtility.LookLikeControls();
		EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField);
		//GUILayout.FlexibleSpace ();
		//Rect r = GUILayoutUtility.GetLastRect ();
		
		string text = "";
		if (value.tagsChange == 0) text = "Nothing";
		else if (value.tagsChange == ~0) text = "Everything";
		else {
			text = System.Convert.ToString (value.tagsChange,2);
		}
		
		string[] tagNames = AstarPath.FindTagNames ();
		
		if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) {
			
			//Debug.Log ("pre");
			GenericMenu menu = new GenericMenu ();
			
			menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet));
			menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet));
			
			for (int i=0;i<tagNames.Length;i++) {
				bool on = (value.tagsChange >> i & 0x1) != 0;
				Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet);
				menu.AddItem (new GUIContent (tagNames[i]),on,value.SetValues, result);
				//value.SetValues (result);
			}
			
			menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags);
			menu.ShowAsContext ();
			
			Event.current.Use ();
			//Debug.Log ("Post");
		}
		
		EditorGUIUtility.LookLikeInspector();
		GUILayout.EndHorizontal ();
		
	}
Beispiel #41
0
 void Start()
 {
     pF = GetComponent <Pathfinding>();
 }
		//
		// Constructors
		//
		public Thread (Pathfinding.WindowsStore.ParameterizedThreadStart start)
		{
			this._taskCancellationTokenSource = new CancellationTokenSource ();
			this._paramThreadStart = start;
		}
	public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
		byte[] bytes = null;
		uint ch = 0;

		// Add a work item since we cannot be sure that pathfinding (or graph updates)
		// is not running at the same time
		AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (force => {
			var sr = new Pathfinding.Serialization.AstarSerializer(script.astarData, settings);
			sr.OpenSerialize();
			script.astarData.SerializeGraphsPart (sr);
			sr.SerializeEditorSettings (graphEditors);
			bytes = sr.CloseSerialize();
			ch = sr.GetChecksum ();
			return true;
		}));

		// Make sure the above work item is executed immediately
		AstarPath.active.FlushWorkItems();
		checksum = ch;
		return bytes;
	}
Beispiel #44
0
 void Start()
 {
     mod = Vector3.zero;
     pathfinding = GetComponent<Pathfinding>();
 }
 public Pathfinding(int width, int height)
 {
     Instance = this;
     grid     = new GridSystem <PathNode>(width, height, 10f, Vector3.zero, (GridSystem <PathNode> g, int x, int y) => new PathNode(g, x, y));
 }
Beispiel #46
0
 //public Node parent;
 // Use this for initialization
 void Start()
 {
     aStar = GameObject.Find("A*").GetComponent <Pathfinding>();
 }
Beispiel #47
0
 void Awake()
 {
     grid = GetComponent<Grid>();
     instance = this;
 }
Beispiel #48
0
        public bool Bodyblock()
        {
            var unitPosition = this.Unit.Position.PredictedByLatency;

            this.targetPosition = this.Target.Position.PredictedByLatency;
            var infront = this.Target.SourceUnit.InFront(1000);

            // infront =
            // this.Target.SourceUnit.InFront(
            // (this.Unit.Position.Current.Distance2D(infront) / this.Unit.SourceUnit.MovementSpeed)
            // * this.Target.SourceUnit.MovementSpeed);
            var backWardsdirection = (this.targetPosition - infront).Normalized();
            var projectionInfo     = Vector3Extensions.ProjectOn(this.targetPosition, unitPosition, infront);
            var projectionInfo2    = Vector3Extensions.ProjectOn(
                unitPosition,
                this.targetPosition + backWardsdirection * (unitPosition.Distance2D(this.targetPosition) + 200),
                infront);
            var distanceFromSegment2 =
                this.Unit.Position.Current.Distance2D(Vector2Extensions.ToVector3(projectionInfo2.SegmentPoint));
            var isCloserToFront = projectionInfo2.SegmentPoint.Distance(infront) + this.Unit.SourceUnit.HullRadius
                                  + this.Target.SourceUnit.HullRadius + 50 < this.targetPosition.Distance2D(infront) &&
                                  unitPosition.Distance2D(infront) < this.targetPosition.Distance2D(infront);
            var angle = this.Unit.SourceUnit.FindRelativeAngle(infront);

            // Console.WriteLine(angle + " " + Math.PI / 4);
            var goodposition = projectionInfo2.IsOnSegment && isCloserToFront;

            this.wasMoving       = this.Unit.SourceUnit.NetworkActivity == NetworkActivity.Move;
            this.targetWasMoving = this.Target.SourceUnit.NetworkActivity == NetworkActivity.Move;
            this.lastRad         = this.Target.SourceUnit.RotationRad;
            var idleTime = this.Target.MovementTracker.IdleTime();

            if (isCloserToFront && idleTime < 1)
            {
                if (this.Unit.TargetSelector.LastDistanceToTarget
                    > this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius
                    + this.Target.SourceUnit.MovementSpeed * (Game.Ping / 1000) * 2 + 200 || angle > Math.PI / 6 ||
                    !goodposition)
                {
                    // Console.WriteLine("1");
                    this.moveOrderWasSent = true;
                    this.Bodyblocking     = true;
                    return
                        (this.Unit.SourceUnit.Move(
                             this.Target.SourceUnit.InFront(
                                 this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 150
                                 + this.Target.SourceUnit.MovementSpeed * (Game.Ping / 1000) * 2)));
                }
            }

            if (goodposition)
            {
                if ((this.wasMoving || this.moveOrderWasSent) && this.Target.SourceUnit.CanMove() && idleTime < 1)
                {
                    // Console.WriteLine("2");
                    this.moveOrderWasSent = false;
                    this.issueSleeper.Sleep(
                        this.IssueSleep
                        + (this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius * 2)
                        / this.Target.SourceUnit.MovementSpeed * 1000);
                    this.Bodyblocking = true;
                    return(this.Stop());
                }

                if (!this.Target.SourceUnit.CanMove() || idleTime >= 1)
                {
                    // Console.WriteLine("3");
                    this.moveOrderWasSent = false;
                    return(this.CantMove());
                }

                // Console.WriteLine("5");
                this.moveOrderWasSent = true;
                this.issueSleeper.Sleep(
                    this.IssueSleep
                    + (this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius)
                    / this.Target.SourceUnit.MovementSpeed * 1000);

                this.Bodyblocking = true;
                return
                    (this.Unit.SourceUnit.Move(
                         this.Target.SourceUnit.InFront(
                             this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 200
                             + this.Target.SourceUnit.MovementSpeed * (Game.Ping / 1000) * 2)));

                return(this.Stop());

                // this.moveOrderWasSent = false;
                return(false);
            }

            // Console.WriteLine("4");
            var canBlock = (this.wasMoving || this.moveOrderWasSent) && goodposition;

            if (!canBlock &&
                (projectionInfo.IsOnSegment ||
                 this.targetPosition.Distance2D(Vector2Extensions.ToVector3(projectionInfo.SegmentPoint))
                 < this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 20))
            {
                var direction  = (infront - this.targetPosition).Normalized();
                var direction1 = (infront - this.targetPosition).Perpendicular().Normalized();
                var direction2 = (this.targetPosition - infront).Perpendicular().Normalized();

                // Console.WriteLine(direction1 + " " + direction2);
                var position = Pathfinding.ExtendUntilWall(
                    this.targetPosition,
                    direction1,
                    Math.Max(
                        this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100,
                        distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var position2 = Pathfinding.ExtendUntilWall(
                    this.targetPosition,
                    direction2,
                    Math.Max(
                        this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100,
                        distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var distance  = unitPosition.Distance2D(position);
                var distance2 = unitPosition.Distance2D(position2);
                if (distance2 < distance)
                {
                    distance = distance2;
                    position = position2;
                }

                if (!isCloserToFront)
                {
                    if (distanceFromSegment2 < this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 50)
                    {
                        infront = Pathfinding.ExtendUntilWall(
                            position,
                            direction,
                            distance + 500,
                            this.Unit.Pathfinder.EnsagePathfinding);
                    }
                    else
                    {
                        infront = Pathfinding.ExtendUntilWall(
                            unitPosition,
                            direction,
                            500,
                            this.Unit.Pathfinder.EnsagePathfinding);
                    }
                }

                // else
                // {
                // infront = Pathfinding.ExtendUntilWall(unitPosition, direction, 300, this.Pathfinder);
                // }
            }
            else
            {
                // if (!this.Target.SourceUnit.CanMove() || !this.targetWasMoving)
                // {
                // this.moveOrderWasSent = false;
                // return this.CantMove();
                // }
                infront =
                    this.Target.SourceUnit.InFront(
                        this.Target.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 300
                        + this.Target.SourceUnit.MovementSpeed * (Game.Ping / 1000) * 2);

                // this.moveOrderWasSent = false;
                // return false;
            }

            this.moveOrderWasSent = true;
            this.Unit.SourceUnit.Move(infront);
            this.Bodyblocking = false;
            return(true);
        }
	// Use this for initialization
	void Start () {
		path = new List<Vector3>();
		pathfinder = GetComponent<Pathfinding>();
		animationator = GetComponent<Animationator>();

	}
Beispiel #50
0
    public IEnumerator TurnCycle(Team team, Team team2)
    {
        while (team.AnySoldierActionsLeft())
        {
            int lastCommand = attackCommand;
            // *** PLAYER ***
            // Right click on any slot moves active unit there.
            GridSlot hitSlot = GetGridUnderMouse();
            if (hitSlot != null)
            {
                MapNode[] path = Pathfinding.FindPathAStar(team.ActiveSoldier.curPositionSlot.transform.position, hitSlot.transform.position, MapGrid.wholeMap);

                // mouse clicks
                if (hitSlot && Input.GetMouseButtonDown(1) && team.ActiveSoldier.NearEnough(path.Length))
                {
                    // shoot at enemy
                    if (hitSlot.HasEnemy())
                    {
                        attackCommand = 1;
                        uiCommandKey  = 0;
                        // Require 2 clicks to auto attack enemy
                        if (!clickedOnce)
                        {
                            clickedOnce = true;
                        }
                        else
                        {
                            clickedOnce   = false;
                            targetedEnemy = hitSlot.taken.soldierId;
                            //flags[0].MoveActiveToRaycastedPoint(hit);
                            team.ActiveSoldier.AttackSlot(hitSlot);
                            SwapSoldierIfNoTurns(team);
                        }
                    }
                    else
                    {
                        // move to slot
                        attackCommand = -1;
                        targetedEnemy = -1;
                        uiCommandKey  = -1;

                        yield return(team.ActiveSoldier.StartCoroutine(MoveToSlot(team, team2, hitSlot, path)));
                    }
                }

                // fire at nearest enemy
                if (Input.GetKeyDown(KeyCode.Alpha1))
                {
                    attackCommand = 2;
                    uiCommandKey  = 0;
                    Soldier nearestEnemy = team2.GetNearestTo(team.ActiveSoldier);
                    if (nearestEnemy)
                    {
                        targetedEnemy = nearestEnemy.soldierId;
                        if (!clickedOnce)
                        {
                            clickedOnce = true;
                        }
                        else
                        {
                            clickedOnce = false;
                            team.ActiveSoldier.AttackSlot(nearestEnemy.curPositionSlot);
                            SwapSoldierIfNoTurns(team);
                        }
                    }
                }

                // grenade throw
                if (hitSlot && Input.GetKeyDown(KeyCode.Alpha3))
                {
                    attackCommand = 3;
                    uiCommandKey  = 2;
                    if (!clickedOnce)
                    {
                        clickedOnce = true;
                    }
                    else
                    {
                        clickedOnce = false;
                        team.ActiveSoldier.AttackSlot(hitSlot, 1);
                        SwapSoldierIfNoTurns(team);
                    }
                }
                // overwatch
                if (Input.GetKeyDown(KeyCode.Alpha2))
                {
                    attackCommand = 4;
                    uiCommandKey  = 1;
                    if (!clickedOnce)
                    {
                        clickedOnce = true;
                    }
                    else
                    {
                        clickedOnce = false;
                        team.ActiveSoldier.ToOverwatch();
                        SwapSoldierIfNoTurns(team);
                    }
                }
                // reload
                if (Input.GetKeyDown(KeyCode.R))
                {
                    attackCommand = 5;
                    uiCommandKey  = 3;
                    if (!clickedOnce)
                    {
                        clickedOnce = true;
                    }
                    else
                    {
                        clickedOnce = false;
                        team.ActiveSoldier.Reload();
                        SwapSoldierIfNoTurns(team);
                    }
                }

                // FIXED: it will work to click on enemy with right click and then 1.
                // makes sure you can't do mouse+something else attack
                if (attackCommand != lastCommand && lastCommand != 0)
                {
                    clickedOnce = false;
                }

                // tabbing swaps units
                if (Input.GetKeyDown(KeyCode.Tab))
                {
                    if (targetedEnemy == -1)
                    {
                        SwapSoldier(team);
                    }
                    else
                    {
                        SwapTarget(team);
                    }
                }

                // *** ENEMIES *** deprecated
                // if enemy moves, trigger all overwatched player's soldiers

                // AI: move all enemies

                /*for (int i = 0; i < team2.units.Count; i++) {
                 *  // trigger player's overwatch
                 *  HandleOverwatchWithoutFog(team2.units[i], team);
                 * }*/
            }
            yield return(null);
        }
    }
Beispiel #51
0
	public Vector3 ApplyVector3(Vector3 to,Vector3 from,Pathfinding.Constraint3 constraints){
		Vector3 result = to;
		if(constraints.a)
			result.x = from.x;
		if(constraints.b)
			result.y = from.y;
		if(constraints.c)
			result.z = from.z;

		return result;
	}
Beispiel #52
0
    public IEnumerator TurnCycle(Team team, Team team2)
    {
        // AI calculations list of commands
        // yield return execute calculated commands and moves
        yield return(new WaitForSeconds(5));

        Debug.Log("End Enemy turn");

        /*stategies:
         * Scoring nearby slots based on utility.
         * n^2 n = around 20 = 400 per character
         *
         */
        for (int i = 0; i < team.units.Count; i++)
        {
            Soldier unit = team.units[i];

            //Generate data for all slots in move range and for soldiers in range that can be attacked. taken move slots are excluded.
            GridSlot[]   slots          = GridSlot.GetAvaliableSlotsInMoveRange(unit.curPositionSlot, unit.fullMovementRange);
            Soldier[]    enemiesInRange = GridSlot.GetVisibleEnemySlots(unit, team2);
            AiSlotData[] moveData       = new AiSlotData[slots.Length];
            AiSlotData[] enemyData      = new AiSlotData[enemiesInRange.Length];
            moveScores  = new int[moveData.Length];
            enemyScores = new int[enemyData.Length];
            for (int j = 0; j < slots.Length; j++)
            {
                moveData[j] = new AiSlotData(slots[j].id);
            }
            for (int j = 0; j < enemyData.Length; j++)
            {
                enemyData[j] = new AiSlotData(enemiesInRange[j].soldierId);
            }
            // Calculations have to be remade for every slots for every enemy. Not good.
            // Utility score.
            // + when enemies are on slot. +100
            // + cover height +0 +50 +100
            // - distance to enemy (gt dist, less)
            //

            /* how to choose to move vs choose to attack
             * just distance
             * */
            // here we choose which actions will be prioritized, movement or shooting.
            int possibleMoveActions = 0;
            int attack = -1;
            if (enemiesInRange.Length == 0)
            {
                continue;
            }
            attack = 0; // shoot, when there are some enemies
            float dist = Vector3.Distance(enemiesInRange[0].transform.position, unit.transform.position);
            if (dist <= unit.movementRange1)
            {
                possibleMoveActions = 1;
            }
            if (enemiesInRange.Length == 0)
            {
                possibleMoveActions = 2;
                attack = -1;
            }

            int bestId = -1;
            int best   = 0;
            // calculates scores for movement slots
            for (int j = 0; j < moveData.Length; j++)
            {
                moveData[j].score = (int)(ClampedReverseDist(unit, unit.fullMovementRange, slots, j)
                                          * MapGrid.CoverScoreMultiplier(slots[j]));
                if (moveData[j].score > best)
                {
                    best   = moveData[j].score;
                    bestId = j;
                }
                moveScores[j] = moveData[j].score;
            }
            GameplayManager.m.moveScores = moveScores;
            int       bestMoveDataId = bestId;
            GridSlot  bestMove       = slots[bestMoveDataId];
            MapNode[] path           = Pathfinding.FindPathAStar(unit.curPositionSlot.transform.position, bestMove.transform.position, MapGrid.wholeMap);
            yield return(unit.StartCoroutine(MoveToSlot(team, team2, bestMove, path)));

            if (attack != -1)
            {
                // calculates scores for enemies
                bestId = -1;
                for (int j = 0; j < enemyData.Length; j++)
                {
                    enemyData[j].score = (int)(ClampedDist(enemiesInRange[j], 100, slots, j)
                                               * MapGrid.CoverScoreMultiplier(enemiesInRange[j].curPositionSlot));
                    if (enemyData[j].score > best)
                    {
                        best   = enemyData[j].score;
                        bestId = j;
                    }
                    enemyScores[j] = enemyData[j].score;
                }
                int bestEnemyDataId = bestId;
                if (bestEnemyDataId != -1)
                {
                    Soldier bestEnemy = enemiesInRange[bestEnemyDataId];

                    unit.AttackSlot(bestEnemy.curPositionSlot);
                    GameplayManager.m.enemyScores = enemyScores;
                }
                else
                {
                    Debug.Log("No enemies in range");
                }
            }

            team.ActiveSoldier.HandleCover();
            SwapSoldier(team);
        }
    }
    Pathfinding pathfinding;            // Reference to the pathfinding script



    // Executes at the start of a game
    private void Awake()
    {
        instance    = this;                         // Makes sure there is only one instance of the class ?
        pathfinding = GetComponent <Pathfinding>(); // Loads the pathfinding functions
    }
Beispiel #54
0
        private void GoingNowhere_OnStateBegin(object sender)
        {
            path.Clear();

            path = Pathfinding.FindPath(GameLoop.World.PathingGrid, Position, Tile.GetCenter(GameLoop.World.GetTile(0, 0)));
        }
	public static void TagsMaskField (GUIContent changeLabel, GUIContent setLabel,ref Pathfinding.TagMask value) {
		
		GUILayout.BeginHorizontal ();
		
		//Debug.Log (value.ToString ());
		EditorGUIUtility.LookLikeControls();
		EditorGUILayout.PrefixLabel (changeLabel,EditorStyles.layerMaskField);
		//GUILayout.FlexibleSpace ();
		//Rect r = GUILayoutUtility.GetLastRect ();
		
		string text = "";
		if (value.tagsChange == 0) text = "Nothing";
		else if (value.tagsChange == ~0) text = "Everything";
		else {
			text = System.Convert.ToString (value.tagsChange,2);
		}
		
		if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) {
			
			
			//Debug.Log ("pre");
			GenericMenu menu = new GenericMenu ();
			
			menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet));
			menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet));
			
			for (int i=0;i<32;i++) {
				bool on = (value.tagsChange >> i & 0x1) != 0;
				Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet);
				menu.AddItem (new GUIContent (""+i),on,value.SetValues, result);
				//value.SetValues (result);
			}
			
			menu.ShowAsContext ();
			
			Event.current.Use ();
			//Debug.Log ("Post");
		}
		
		EditorGUIUtility.LookLikeInspector();
		GUILayout.EndHorizontal ();
		
		
		
		GUILayout.BeginHorizontal ();
		
		//Debug.Log (value.ToString ());
		EditorGUIUtility.LookLikeControls();
		EditorGUILayout.PrefixLabel (setLabel,EditorStyles.layerMaskField);
		//GUILayout.FlexibleSpace ();
		//r = GUILayoutUtility.GetLastRect ();
		
		text = "";
		if (value.tagsSet == 0) text = "Nothing";
		else if (value.tagsSet == ~0) text = "Everything";
		else {
			text = System.Convert.ToString (value.tagsSet,2);
		}
		
		if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) {
			
			
			//Debug.Log ("pre");
			GenericMenu menu = new GenericMenu ();
			
			if (value.tagsChange != 0)	menu.AddItem (new GUIContent ("Everything"),value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,~0));
			else				menu.AddDisabledItem (new GUIContent ("Everything"));
			
			menu.AddItem (new GUIContent ("Nothing"),value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,0));
			
			for (int i=0;i<32;i++) {
				bool enabled = (value.tagsChange >> i & 0x1) != 0;
				bool on = (value.tagsSet >> i & 0x1) != 0;
				
				Pathfinding.TagMask result = new Pathfinding.TagMask (value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1<<i);
				
				if (enabled)	menu.AddItem (new GUIContent (""+i),on,value.SetValues, result);
				else	menu.AddDisabledItem (new GUIContent (""+i));
				
				//value.SetValues (result);
			}
			
			menu.ShowAsContext ();
			
			Event.current.Use ();
			//Debug.Log ("Post");
		}
		
		EditorGUIUtility.LookLikeInspector();
		GUILayout.EndHorizontal ();
		
		
		//return value;
	}
Beispiel #56
0
    public virtual IEnumerator TurnSequence(List <Vector3> currentUnwalkables)
    {
        UnitStateChange(UnitState.BUSY);

        currentUnwalkables.Remove(transform.position);

        //List of possible paths to a targets
        List <PathNode> chosenPath = new List <PathNode>();
        GameObject      target     = null;

        //Find all players
        GameObject[] targets = GameObject.FindGameObjectsWithTag("Player");

        int minPathLength = boardRows * boardColumns;

        foreach (GameObject t in targets)
        {
            currentUnwalkables.Remove(t.transform.position); //Make sure the target is reachable.

            Pathfinding pathfinding = new Pathfinding(boardColumns, boardRows, currentUnwalkables);

            currentUnwalkables.Add(t.transform.position); //Reinsert target for the next iteration.

            List <PathNode> path = pathfinding.FindPath((int)transform.position.x, (int)transform.position.y, (int)t.transform.position.x, (int)t.transform.position.y);

            if (path != null && path.Count < minPathLength)
            {
                minPathLength = path.Count;
                chosenPath    = path;
                target        = t;
            }
        }

        /*
         * if (chosenPath == null || target == null)
         * {
         *  Debug.Log("No possible routes to targets!");
         *  EndTurn();
         *  yield return null;
         * }
         *
         *
         * //yield return new WaitForSecondsRealtime(1);
         * if (chosenPath.Count == 0)
         * {
         *  yield return StartCoroutine(EnemyAbility(target));
         *  yield return null;
         * }
         *
         * foreach (PathNode pn in chosenPath)
         * {
         *  Debug.Log(pn.coord);
         *  facingDirection = Vector3.Normalize(pn.coord - transform.position);
         *  ChangeFacingDirection(facingDirection);
         *  yield return StartCoroutine(Move((int)facingDirection.x, (int)facingDirection.y));
         *
         *  if (currentHealth <= 0)
         *  {
         *      yield break;
         *  }
         *
         *  if (Vector3.Distance(transform.position, target.transform.position) <= 1)
         *  {
         *      yield return StartCoroutine(EnemyAbility(target));
         *  }
         * }*/

        EndTurn();
        yield return(null);
    }
		public Thread (Pathfinding.WindowsStore.ThreadStart start)
		{
			this._taskCancellationTokenSource = new CancellationTokenSource ();
			this._threadStart = start;
		}
Beispiel #58
0
 private void Start()
 {
     pathfinder = GetComponent <Pathfinding>();
     rb2d       = GetComponent <Rigidbody2D>();
 }
 void Awake()
 {
     instance = this;
     pathfinding = GetComponent<Pathfinding> ();
 }
Beispiel #60
0
 private void Start()
 {
     Instance = this;
     gc       = FindObjectOfType <GameController>();
 }