/// <summary> /// Generates the noise map. /// From https://stackoverflow.com/questions/8659351/2d-perlin-noise /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="result">The result.</param> /// <param name="octaves">The octaves.</param> public static void GenerateNoiseMap(int width, int height, int octaves, out DoubleOrSingle[] result) { var data = new DoubleOrSingle[width * height]; // track min and max noise value. Used to normalize the result to the 0 to 1.0 range. var min = DoubleOrSingle.MaxValue; var max = DoubleOrSingle.MinValue; // rebuild the permutation table to get a different noise pattern. // Leave this out if you want to play with changing the number of octaves while // maintaining the same overall pattern. Noise2d.Reseed(); var frequency = 0.5f; var amplitude = 1f; //var persistence = 0.25f; for (var octave = 0; octave < octaves; octave++) { // parallel loop - easy and fast. Parallel.For(0 , width * height , (offset) => { var i = offset % width; var j = offset / width; var noise = Noise2d.Noise(i * frequency * 1f / width, j * frequency * 1f / height); noise = data[j * width + i] += noise * amplitude; min = Math.Min(min, noise); max = Math.Max(max, noise); } ); frequency *= 2; amplitude /= 2; } //Normalize for (int i = 0; i < data.Length; ++i) { data[i] = (data[i] - min) / (max - min); } result = data; }
public void AddObstacles() { int width = MapConstants.mapWidth - 2; int height = MapConstants.mapHeight - 2; var data = new float[width * height]; var min = float.MaxValue; var max = float.MinValue; Noise2d.Reseed(); var frequency = 0.1f; var amplitude = 1f; for (int i = 0; i < data.Length; i++) { var x = i % width; var y = i / width; var noise = Noise2d.Noise(x * frequency * 1f / width, y * frequency * 1f / height); noise = data[y * width + x] += noise * amplitude; min = Math.Min(min, noise); max = Math.Max(max, noise); } for (int i = 1; i < MapConstants.mapHeight - 1; i++) { for (int j = 1; j < MapConstants.mapWidth - 1; j++) { var normalizedNoise = (data[(i - 1) * (j - 1)] - min) / (max - min); var obstacle = GetObstacleByNoise(normalizedNoise); if (obstacle != null) { map[i, j] = obstacle; } } } }