Noise.cs 1.7 KB

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