Noise.cs 2.2 KB

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