public void GenerateMap(MapGrid mapGrid) { var nodeGoList = new List <MapNodeGameObject>(); // First we calculate the bounds of our map float xMax = 0, xMin = 0, yMax = 0, yMin = 0; foreach (var point in mapCollider.points) { xMax = (xMax < point.x) ? point.x : xMax; xMin = (xMin > point.x) ? point.x : xMin; yMax = (yMax < point.y) ? point.y : yMax; yMin = (yMin > point.y) ? point.y : yMin; } // Calculate the needed iterations var iterationsX = Mathf.FloorToInt((Mathf.Abs(xMax) + Mathf.Abs(xMin)) / rootNodeDistance); var iterationsY = Mathf.FloorToInt((Mathf.Abs(yMax) + Mathf.Abs(yMin)) / rootNodeDistance); mapGrid.SetNodeDimensions(iterationsX, iterationsY); // Then we iterate through the bounds and create our root nodes for (int yCount = 0; yCount < iterationsY; yCount++) { for (int xCount = 0; xCount < iterationsX - 1; xCount++) { // Calculate position, justified by mapCollider pos var position = new Vector3(xMin + (rootNodeDistance * xCount), yMin + (rootNodeDistance * yCount)) + mapCollider.transform.position; // Check placement if (!mapCollider.OverlapPoint(position)) { continue; } bool collides = false; foreach (var o in obstacleColliders) { if (o.OverlapPoint(position)) { collides = true; break; } } if (collides) { continue; } // Add a random vector var randAdjustedPosition = position + (new Vector3(Random.Range(0, 1f), Random.Range(0, 1f)) * rootNodeDistance / 2f); // Check placement again, just to be sure // Otherwise revert to original pos var spawnPos = mapCollider.OverlapPoint(position) ? randAdjustedPosition : position; // Create the data model var nodeModel = new MapNode() { Position = new Vector2(xCount, yCount), WorldPosition = spawnPos }; // Spawn the node var rootNodeGo = Instantiate(mapPrefabs.rootNodePrefab, spawnPos, Quaternion.identity, mapRootNodesTransform); rootNodeGo.GetComponent <MapNodeGameObject>().Data = nodeModel; nodeGoList.Add(rootNodeGo.GetComponent <MapNodeGameObject>()); // Add the node to the grid model mapGrid.AddNode(nodeModel); } } // Set neighbours for the node foreach (var node in mapGrid.ListNodes) { node.Neighbours = mapGrid.GetNeighbours(node); node.DeeperNeighbours = mapGrid.GetDeeperNeighbours(node); } mapCollider.enabled = false; }