using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MakeForest1 : MonoBehaviour
{
[SerializeField] private int width;
[SerializeField] private int height;
[SerializeField] private string seed;
[SerializeField] private bool useRandomSeed;
[Range(0, 100)]
[SerializeField] private int randomeFillPercent;
[SerializeField] private int smoothNum;
[SerializeField] private int interval;
[SerializeField] private int treeRand;
[SerializeField] private int startArea;
private int[,] map;
private const int Road = 0;
private const int Wall = 1;
public GameObject treeOj;
private void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
GenerateMap();
}
}
private void GenerateMap()
{
map = new int[width, height];
MapRandomFill();
for (int i = 0; i < smoothNum; i++)
{
SmoothMap();
}
SetTree();
}
private void SetTree()
{
for (int x = 0; x < width; x += interval)
{
for (int y = 0; y < height; y += interval)
{
if (map[x, y] == Wall)
{
int randX = UnityEngine.Random.Range(-treeRand, treeRand + 1);
int randY = UnityEngine.Random.Range(-treeRand, treeRand + 1);
Instantiate(treeOj, new Vector3(x - (width * 0.5f) + (interval * 0.5f) + randX, 0, y - (height * 0.5f) + (interval * 0.5f) + randY), Quaternion.identity);
}
}
}
}
private void MapRandomFill()
{
if (useRandomSeed)
{
seed = Time.time.ToString();
}
System.Random rand = new System.Random(seed.GetHashCode());
for (int x = 0; x < width; x += interval)
{
for (int y = 0; y < height; y += interval)
{
map[x, y] = rand.Next(0, 100) < randomeFillPercent ? Wall : Road;
}
}
}
private void SmoothMap()
{
for (int x = 0; x < width; x += interval)
{
for (int y = 0; y < height; y += interval)
{
int neighbourWallTiles = GetSurroundingWallCount(x, y);
if (neighbourWallTiles > 4)
{
map[x, y] = Wall;
}
else if (neighbourWallTiles < 4)
{
map[x, y] = Road;
}
if (x < (width * 0.5 + startArea - interval) && x > (width * 0.5 - startArea) && y < (height * 0.5 + startArea - interval) && y > (height * 0.5 - startArea))
{
map[x, y] = Road;
}
}
}
}
private int GetSurroundingWallCount(int gridX, int gridY)
{
int wallCount = 0;
for (int neighbourX = gridX - interval; neighbourX <= gridX + interval; neighbourX += interval)
{
for (int neighbourY = gridY - interval; neighbourY <= gridY + interval; neighbourY += interval)
{
if ((neighbourX >= 0) && (neighbourX < width) && (neighbourY >= 0) && neighbourY < height)
{
if (neighbourX != gridX || neighbourY != gridY)
{
wallCount += map[neighbourX, neighbourY];
}
}
else wallCount++;
}
}
return wallCount;
}
}