ChunkTerrainGenerator.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using KairoEngine.Chunks;
  5. using Sirenix.OdinInspector;
  6. namespace KairoEngine.TerrainEngine
  7. {
  8. public class ChunkTerrainGenerator : MonoBehaviour
  9. {
  10. public MarchingCubes3 marchingCubes3;
  11. public MarchingCubes2 marchingCubes2;
  12. public Vector3Int chunkSize = new Vector3Int(16, 16, 16);
  13. public Vector3Int chunks = new Vector3Int(2, 1, 2);
  14. public float noiseMultiplier = 1.5f;
  15. public ChunkSystem<BlockBase> chunkSystem;
  16. [Button("Generate")]
  17. void CreateChunks()
  18. {
  19. chunkSystem = new ChunkSystem<BlockBase>(chunkSize, true);
  20. for (int x = 0; x < chunks.x; x++) {
  21. for (int z = 0; z < chunks.z; z++) {
  22. for (int y = 0; y < chunks.y; y++) {
  23. Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  24. chunkSystem.CreateChunk(chunkPos, (Chunk<BlockBase> c, Vector3Int pos) => new BlockBase(0, 0));
  25. GenerateChunkTerrain(chunkPos);
  26. }
  27. }
  28. }
  29. for (int x = 0; x < chunks.x; x++) {
  30. for (int z = 0; z < chunks.z; z++) {
  31. for (int y = 0; y < chunks.y; y++) {
  32. Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  33. if(marchingCubes3 != null) marchingCubes3.Generate(chunkSystem, chunkPos);
  34. else if(marchingCubes2 != null) marchingCubes2.Generate(chunkSystem, chunkPos);
  35. }
  36. }
  37. }
  38. }
  39. void GenerateChunkTerrain(Vector3Int initialPos)
  40. {
  41. for (int x = 0; x < chunkSize.x; x++) {
  42. for (int z = 0; z < chunkSize.z; z++) {
  43. for (int y = 0; y < chunkSize.y; y++) {
  44. // Get a terrain height using regular old Perlin noise.
  45. Vector3Int pos = initialPos + new Vector3Int(x, y, z);
  46. float width = (float)(chunks.x * chunkSize.x);
  47. float height = (float)(chunks.y * chunkSize.y);
  48. float length = (float)(chunks.z * chunkSize.z);;
  49. float thisHeight = height * Mathf.PerlinNoise((float)pos.x / width * noiseMultiplier + 0.001f, (float)pos.z / length * noiseMultiplier + 0.001f);
  50. BlockBase block = new BlockBase(0, (uint)Mathf.FloorToInt(thisHeight * 1000));
  51. chunkSystem.SetBlock(pos, block);
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }