Skip to content

Instantly share code, notes, and snippets.

@twiddles
Created July 24, 2023 21:24
Show Gist options
  • Save twiddles/7eba7790105bf72bb7be4ad6d921e646 to your computer and use it in GitHub Desktop.
Save twiddles/7eba7790105bf72bb7be4ad6d921e646 to your computer and use it in GitHub Desktop.
Procedure Level Generator
public void Initialize(int newWidth, int newHeight)
{
Random.InitState(seed + GameManager.Instance.currentLevel);
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
width = newWidth;
height = newHeight;
int exitPositionX;
int exitPositionY;
bool topBottom;
if (GameManager.Instance.currentLevel == 0)
{
exitPositionX = Random.Range(1, width - 1);
exitPositionY = height - 1;
topBottom = true;
}
else
{
topBottom = Random.Range(0.0f, 1.0f) >= .5f;
if (topBottom)
{
exitPositionX = Random.Range(1, width - 1);
exitPositionY = Random.Range(0.0f, 1.0f) >= .5f ? 0 : height - 1;
}
else
{
exitPositionX = Random.Range(0.0f, 1.0f) >= .5f ? 0 : width - 1;
exitPositionY = Random.Range(1, height - 1);
}
}
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
// Outer Walls
if (x == 0 || x == (width - 1) || y == 0 || y == (height - 1))
{
//Debug.LogWarning($"Trying Exit Spawn: {x}, {y} <- {exitPositionX}, {exitPositionY}");
if (x == exitPositionX && y == exitPositionY)
{
// place exit
SpawnAt(exitTile, x, y, topBottom ? 0.0f : 90.0f);
}
else
{
SpawnAt(wallTile, x, y, 0.0f);
}
}
else
{
// Inner Tile Logic
SpawnAt(floorTiles[Random.Range(0, floorTiles.Length)], x, y, 0.0f, 0.0f, true);
if (Random.Range(0.0f, 1.0f) < enemyChance)
{
// only spawn enemies after 3rd level
if (GameManager.Instance.currentLevel > 1)
SpawnAt(enemies[Random.Range(0, enemies.Length)], x, y);
}
else if (Random.Range(0.0f, 1.0f) < propsChance)
{
SpawnAt(propTiles[Random.Range(0, propTiles.Length)], x, y);
}
else
{
if (Random.Range(0.0f, 1.0f) < woodenStructTileChance)
{
SpawnAt(woodenStructTile, x, y);
if (Random.Range(0.0f, 1.0f) > 0.6f)
{
SpawnAt(bannerTile, x, y);
}
}
else if (Random.Range(0.0f, 1.0f) < columnChance)
{
SpawnAt(columnTile, x, y);
}
}
// pickups
if (GameManager.Instance.currentLevel > 0)
if (Random.Range(0.0f, 1.0f) < pickupChance)
{
SpawnAt(pickups[Random.Range(0, pickups.Length)], x, y);
}
}
}
}
AstarPath.active.Scan();
}
private void SpawnAt(Transform tile, int x, int y, float rotationY = 0.0f, float heightOffset = 0.0f,
bool force = false)
{
// Don't spawn at player spawn
if (!force && x - width / 2 == 0 && y - height / 2 == 0) return;
// Debug.LogWarning($"Spawning {tile.name} at {x - width / 2}, {y - height / 2}");
Instantiate(tile, new Vector3(x - width / 2, heightOffset, y - height / 2), Quaternion.Euler(0, rotationY, 0),
transform);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment