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 using multiple layers of Perlin noise in a 2D Unity game, follow these steps: 1. Create a new 2D Unity project. 2. Create a new C# script called `MapGenerator` and open it in your code editor. 3. Add the following code to the `MapGenerator` script: ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapGenerator : MonoBehaviour { public int mapWidth; public int mapHeight; public float noiseScale; public int octaves; [Range(0, 1)] public float persistance; public float lacunarity; public int seed; public Vector2 offset; public void GenerateMap() { float[,] noiseMap = GenerateNoiseMap(mapWidth, mapHeight, seed, noiseScale, octaves, persistance, lacunarity, offset); } 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 (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; } 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 - width / 2f) / scale * frequency + octaveOffsets[i].x; float sampleY = (y - height / 2f) / scale * frequency + octaveOffsets[i].y; float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1; noiseHeight += perlinValue * amplitude; amplitude *= persistance; frequency *= lacunarity; } noiseMap[x, y] = noiseHeight; } } return noiseMap; } } ``` 4. Attach the `MapGenerator` script to an empty GameObject in your scene. 5. Adjust the parameters in the Inspector as needed, such as map width, map height, noise scale, octaves, persistance, lacunarity, and seed. 6. Call the `GenerateMap()` function from another script or by adding a button in the Unity editor to generate a new map. This script will generate a 2D noise map using multiple layers of Perlin noise. You can use this noise map to create a tile-based map or apply it to a texture to create a heightmap for terrain.