Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
ProjectBackup/Unity/Landmass Generation/Assets/Scripts/Utils/Noise.cs
2022-11-12 13:10:03 +01:00

56 lines
2.1 KiB
C#

using UnityEngine;
namespace Utils {
public static class Noise {
public static float[,] GenerateNoiseMap(int width, int height, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) {
float[,] noiseMap = new float[width, height];
System.Random prng = new System.Random(seed);
Vector2[] octaveOffsets = new Vector2[octaves];
for (var i = 0; i < octaveOffsets.Length; i++) {
float offsetX = prng.Next(-100000, 100000) + offset.x;
float offsetY = prng.Next(-100000, 100000) + offset.y;
octaveOffsets[i] = new Vector2(offsetX, offsetY);
}
if (scale <= 0) scale = 0.0001f;
float maxNoiseHeight = float.MinValue;
float minNoiseHeight = float.MaxValue;
float halfWidth = width / 2f;
float halfHeight = height / 2f;
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
float amplitude = 1;
float frequency = 1;
float noiseHeight = 0;
for (int i = 0; i < octaves; i++) {
float sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
float sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;
float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
noiseHeight += perlinValue * amplitude;
amplitude *= persistance;
frequency *= lacunarity;
}
if (noiseHeight > maxNoiseHeight) maxNoiseHeight = noiseHeight;
if (noiseHeight < minNoiseHeight) minNoiseHeight = noiseHeight;
noiseMap[x, y] = noiseHeight;
}
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
}
return noiseMap;
}
}
}