UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create a random map generation system with multiple layers of perlin noise for a 2d unity game"
To create a random map generation system with multiple layers of Perlin noise for a 2D Unity game, follow these steps: 1. Create a new 2D Unity project. 2. Create a new script called `MapGenerator` and paste the following code inside: ```csharp using UnityEngine; public class MapGenerator : MonoBehaviour { public int width; public int height; public float scale; public int octaves; public float persistence; public float lacunarity; public int seed; public Vector2 offset; private void Start() { GenerateMap(); } public void GenerateMap() { float[,] noiseMap = GenerateNoiseMap(width, height, scale, octaves, persistence, lacunarity, seed, offset); // Here you can use the noiseMap to create your map using tiles, sprites or any other method you prefer. } private float[,] GenerateNoiseMap(int mapWidth, int mapHeight, float scale, int octaves, float persistence, float lacunarity, int seed, Vector2 offset) { float[,] noiseMap = new float[mapWidth, mapHeight]; System.Random prng = new System.Random(seed); Vector2[] octaveOffsets = new Vector2[octaves]; for (int i = 0; i < octaves; 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; for (int y = 0; y < mapHeight; y++) { for (int x = 0; x < mapWidth; x++) { float amplitude = 1; float frequency = 1; float noiseHeight = 0; for (int i = 0; i < octaves; i++) { float sampleX = (x - mapWidth / 2f) / scale * frequency + octaveOffsets[i].x; float sampleY = (y - mapHeight / 2f) / scale * frequency + octaveOffsets[i].y; float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1; noiseHeight += perlinValue * amplitude; amplitude *= persistence; frequency *= lacunarity; } if (noiseHeight > maxNoiseHeight) { maxNoiseHeight = noiseHeight; } else if (noiseHeight < minNoiseHeight) { minNoiseHeight = noiseHeight; } noiseMap[x, y] = noiseHeight; } } for (int y = 0; y < mapHeight; y++) { for (int x = 0; x < mapWidth; x++) { noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]); } } return noiseMap; } } ``` 3. Attach the `MapGenerator` script to an empty GameObject in your scene. 4. Set the values for `width`, `height`, `scale`, `octaves`, `persistence`, `lacunarity`, `seed`, and `offset` in the Inspector according to your preferences. 5. Implement your preferred method of creating the map using the generated `noiseMap` in the `GenerateMap()` function. You can use tilemaps, instantiate prefabs, or any other method to create your 2D map based on the Perlin noise values. This script will generate a random map using multiple layers of Perlin noise. You can tweak the parameters to achieve the desired look for your map.