public Vector2 GetDirection() { if (board == null) { board = FindObjectOfType <Board>(); } if (game == null) { game = FindObjectOfType <Game>(); } if (player == null) { player = FindObjectOfType <Player>(); } if (navigation == null) { navigation = FindObjectOfType <Navigation>(); } if (moveRandomlyTime > 0) { return(GetRandomDirection()); } if (grid == null) { grid = (Instantiate(navigation.waypointGridPrefab, transform) as GameObject).GetComponent <WaypointGrid>(); grid.waypointX = (int)Mathf.Round(player.transform.position.x); grid.waypointY = (int)Mathf.Round(player.transform.position.y); Debug.Log("Waypoint grid created"); } if (Random.value > 0.995f) { ResetWaypoint(); } Navigation.Pair p = navigation.DirectionToWaypoint(grid, (int)Mathf.Round(enemy.transform.position.x), (int)Mathf.Round(enemy.transform.position.y), flee); if (p.x == 0 && p.y == 0) { ResetWaypoint(); p = navigation.DirectionToWaypoint(grid, (int)Mathf.Round(enemy.transform.position.x), (int)Mathf.Round(enemy.transform.position.y), flee); } if (WouldCollide(p) || (p.x == 0 && p.y == 0)) { moveRandomlyTime = 5f; return(GetRandomDirection()); } return(new Vector2(p.x, p.y)); }
public Pair DirectionToWaypoint(WaypointGrid grid, int startX, int startY, bool flee = false) { int x = startX; int y = startY; Pair bestDirection = new Pair(0, 0); int bestDistance = grid[x, y];//it's possible best bet is to stay Pair direction = new Pair(0, -1); int d = grid[x + direction.x, y + direction.y]; if (flee) { bestDistance = 0; if (d > bestDistance && d < 1000) { bestDistance = d; bestDirection = direction; } direction = new Pair(0, 1); d = grid[x + direction.x, y + direction.y]; if (d > bestDistance && d < 1000) { bestDistance = d; bestDirection = direction; } direction = new Pair(-1, 0); d = grid[x + direction.x, y + direction.y]; if (d > bestDistance && d < 1000) { bestDistance = d; bestDirection = direction; } direction = new Pair(1, 0); d = grid[x + direction.x, y + direction.y]; if (d > bestDistance && d < 1000) { bestDistance = d; bestDirection = direction; } return(bestDirection); } //first try up if (d <= bestDistance) { bestDistance = d; bestDirection = direction; } //down direction = new Pair(0, 1); d = grid[x + direction.x, y + direction.y]; if (d <= bestDistance) { bestDistance = d; bestDirection = direction; } //left direction = new Pair(-1, 0); d = grid[x + direction.x, y + direction.y]; if (d <= bestDistance) { bestDistance = d; bestDirection = direction; } //right direction = new Pair(1, 0); d = grid[x + direction.x, y + direction.y]; if (d <= bestDistance) { bestDistance = d; bestDirection = direction; } if (bestDistance > 1000) { return(new Pair(0, 0)); } return(bestDirection); }
public static void init() { grid = new WaypointGrid(); }