Noise.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using UnityEngine;
  2. public static class Noise
  3. {
  4. public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset)
  5. {
  6. float[,] noiseMap = new float[mapWidth, mapHeight];
  7. System.Random prng = new System.Random(seed);
  8. Vector2[] octaveOffsets = new Vector2[octaves];
  9. for (int i=0; i<octaves; i++)
  10. {
  11. float offsetX = prng.Next(-100000, 100000) + offset.x;
  12. float offsetY = prng.Next(-100000, 100000) + offset.y;
  13. octaveOffsets[i] = new Vector2(offsetX, offsetY);
  14. }
  15. if(scale <= 0)
  16. {
  17. scale = .0001f;
  18. }
  19. float maxNoiseHeight = float.MinValue;
  20. float minNoiseHeight = float.MaxValue;
  21. float halfWidth = mapWidth / 2;
  22. float halfHeight = mapHeight / 2;
  23. for(int y = 0; y < mapHeight; y++)
  24. {
  25. for(int x = 0; x < mapWidth; x++)
  26. {
  27. float amplitude = 1;
  28. float frequency = 1;
  29. float noiseHeight = 0;
  30. for(int i=0; i<octaves; i++)
  31. {
  32. float sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
  33. float sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;
  34. float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
  35. noiseHeight += perlinValue * amplitude;
  36. amplitude *= persistance;
  37. frequency *= lacunarity;
  38. }
  39. if (noiseHeight > maxNoiseHeight)
  40. {
  41. maxNoiseHeight = noiseHeight;
  42. }
  43. else if(noiseHeight < minNoiseHeight)
  44. {
  45. minNoiseHeight = noiseHeight;
  46. }
  47. noiseMap[y, x] = noiseHeight;
  48. }
  49. }
  50. for (int y = 0; y < mapHeight; y++)
  51. {
  52. for (int x = 0; x < mapWidth; x++)
  53. {
  54. noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
  55. }
  56. }
  57. return noiseMap;
  58. }
  59. }