I have this code that works great for placing objects procedurally. However, the perlin noise is inconsistent, and it slightly changes when it is updated with new player position values. Any fixes for this?
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
public class ChunkGenerationScript : MonoBehaviour
{
public int gridSizeX = 5;
public int gridSizeY = 5;
public int ChunkScale;
public float NoiseScale, NoiseHeight;
public GameObject Floor1, Floor2, Floor3;
public Transform Player;
public int Seed;
public float RequiredHeight;
Vector2 PreviousPos;
Vector2 PlayerPos;
public int DistanceToChange;
void Start()
{
PreviousPos = new Vector2(Player.position.x, Player.position.z);
}
private void Update()
{
PlayerPos = new Vector2(Mathf.Floor(Player.transform.position.x), Mathf.Floor(Player.transform.position.z));
if (Vector2.Distance(PreviousPos, PlayerPos) > DistanceToChange) SpawnGrid();
}
public void SpawnGrid()
{
Random.InitState(Seed);
ClearGrid();
PreviousPos = PlayerPos;
for (int x = 0; x < gridSizeX; x++)
{
for (int y = 0; y < gridSizeY; y++)
{
float xCoord = (((PlayerPos.x / ChunkScale) + x) / gridSizeX) * NoiseScale * Seed;
float zCoord = (((PlayerPos.y / ChunkScale) + y) / gridSizeY) * NoiseScale * Seed;
float Result = Mathf.PerlinNoise(xCoord, zCoord);
Vector3 position = new Vector3(x * ChunkScale + PlayerPos.x, 0, y * ChunkScale + PlayerPos.y) - (new Vector3(gridSizeX, 0, gridSizeY) * ChunkScale / 2);
GameObject prefab;
if (Result >= RequiredHeight) prefab = Floor1;
else prefab = Floor2;
GameObject NewChunk = Instantiate(prefab, transform, transform);
NewChunk.transform.localPosition = position;
NewChunk.transform.localScale *= ChunkScale / 10;
}
}
}
public void ClearGrid()
{
for (int i = transform.childCount - 1; i >= 0; i--)
{
DestroyImmediate(transform.GetChild(i).gameObject);
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(ChunkGenerationScript))]
public class GridSpawnerEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
ChunkGenerationScript gridSpawner = (ChunkGenerationScript)target;
if (GUILayout.Button("Spawn Grid"))
{
gridSpawner.SpawnGrid();
}
if (GUILayout.Button("Clear Grid"))
{
gridSpawner.ClearGrid();
}
}
}
#endif
}