Hi. I’m trying to make navigation work on a runtime-generated 2D level. I managed to make a grid on runtime, but I’m stuck on units not moving.
2 units on the left are supposed to move towards orange tank. Debug section of AILerp shows that a path is pending all the time.
And here is a script of the level generator:
public class BattleGenerator : MonoBehaviour
{
[SerializedDictionary("Terrain","Obstacles")]
public SerializedDictionary<GameObject, GameObject[]> terrainToObstacles;
public int size;
private Dictionary<Vector2, bool> _occupiedByObstacle=new Dictionary<Vector2, bool>();
public GameObject[] enemyTypes;
public GameObject playerTank,ui;
private const float _cellSize=0.64f;
private List<GameObject> obstacleObjects = new List<GameObject>();
private void Start()
{
AstarData astarData = AstarPath.active.data;
astarData.FindGraphTypes();
GridGraph gridGraph = astarData.AddGraph(typeof(GridGraph)) as GridGraph;
gridGraph.SetDimensions(size*7, size*7,0.1f);
gridGraph.center = new Vector3(size/2f*_cellSize-size, size/2f*_cellSize);
gridGraph.collision.diameter = 6;
gridGraph.is2D = true;
gridGraph.collision.use2D = true;
gridGraph.collision.mask=LayerMask.GetMask("Obstacles");
int randomInt = UnityEngine.Random.Range(0, 3);
GameObject randomTerrain = new List<GameObject>(terrainToObstacles.Keys)[randomInt];
GameObject[] obstacles = terrainToObstacles[randomTerrain];
List<Vector2> allPositions = new List<Vector2>();
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Vector2 position = new Vector2(i*_cellSize-size, j*_cellSize);
Instantiate(randomTerrain, position, Quaternion.identity);
if (Random.Range(0, 20) == 0)
{
GameObject obstacle=Instantiate(obstacles[Random.Range(0, obstacles.Length-1)],position,Quaternion.Euler(0, 0, Random.Range(0, 359)));
_occupiedByObstacle.Add(position,true);
obstacleObjects.Add(obstacle);
}
else
{
_occupiedByObstacle.Add(position,false);
}
allPositions.Add(position);
}
}
int enemyCount = Random.Range(10, 20);
int placedEnemies = 0;
while (placedEnemies<enemyCount)
{
GameObject enemy=Instantiate(enemyTypes[Random.Range(0, enemyTypes.Length - 1)],
allPositions[Random.Range(0, allPositions.Count / 2) - 1],
Quaternion.Euler(0, 0, Random.Range(0, 359)));
placedEnemies++;
StateTracker.instance.enemyCount++;
enemy.GetComponent<IComputerUnit>().SetTeam(1);
}
bool playerPlaced = false;
while (!playerPlaced)
{
Vector2 randomLowerPosition =
allPositions[Random.Range((allPositions.Count / 2) - 1, allPositions.Count - 1)];
if (!_occupiedByObstacle[randomLowerPosition])
{
GameObject player=Instantiate(playerTank, randomLowerPosition, Quaternion.identity);
playerPlaced = true;
ui.GetComponent<UserInterface>().tank = player;
}
}
AstarPath.active.Scan();
}
}