public Vector Execute(Tank tank, int timeElapsed) { Vector steeringForce = new Vector(0, 0); //Keep following path until finished if (tank.PlayerInAttackZone()) { ClearPath(); tank.ChangeState(new TankAttackPlayer()); } else if (tank.PlayerNotSeenAtLastLocation()) { ClearPath(); tank.ChangeState(new TankPatrol(tank)); } else if (path.Count == 0) { tank.gameWorld.GridLogic.CalculateNeighborsEntities(tank, Tank.MaxRadiusOfTankSeight); foreach (MovingEntity entity in tank.gameWorld.GridLogic.EntitiesInRange) { if (entity is Player) { searchAStar = new SearchAStar(tank, entity.InCell); searchAStar.Search(); path = searchAStar.GetPathToTarget(); if (path.Count == 0) { return(steeringForce); } //Path starts from end of list so the path following needs to be started at the end of the list i = path.Count - 1; steeringForce = seek.Execute(tank, path[i].Position) * GlobalVars.SeekingWeight; } } } else { if (i > 0) { //Seek current cell in path steeringForce = seek.Execute(tank, path[i].Position) * GlobalVars.SeekingWeight; // steeringForce += avoid.Execute(tank) * GlobalVars.ObstacleAvoidanceWeight; //go to next step in path if the tank approximatly reached the cell if (tank.DistanceToPosition(path[i].Position) <= GlobalVars.cellSize / 2) { i--; } } else { ClearPath(); } } return(steeringForce); }
/// <summary> /// Attempts to move this enemy towards the player. /// </summary> public void SeekPlayer() { var playerObj = FindObjectOfType <Player>(); var pathFinder = new SearchAStar(this, transform.position, playerObj.transform.position, new ManhattanDistance(playerObj.transform.position)); var destination = pathFinder.Search(); if (destination == null) { Debug.Log("Pathfinding: Enemy cannot find valid path to target! " + transform); return; } var direction = destination[0].Destination - (Vector2)transform.position; AttemptMove <Component>((int)direction.x, (int)direction.y); }