├── .gitattributes ├── 00_Start_Project.unitypackage ├── 01_End_Project.unitypackage ├── LICENSE ├── README.md └── Scripts ├── MapGenerator.cs ├── MapRenderer.cs ├── NoiseHelper.cs ├── NoiseSettings.cs ├── PerlinWorm.cs └── RiverGenerator.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /00_Start_Project.unitypackage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SunnyValleyStudio/Perlin-Worms-Unity-tutorial/fdd62459725360bc61a25fcfc0c7516f202bfa24/00_Start_Project.unitypackage -------------------------------------------------------------------------------- /01_End_Project.unitypackage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SunnyValleyStudio/Perlin-Worms-Unity-tutorial/fdd62459725360bc61a25fcfc0c7516f202bfa24/01_End_Project.unitypackage -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 SunnyValleyStudio 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Perlin-Worms-Unity-tutorial 2 | [![Tutorial](http://img.youtube.com/vi/B8qarIAuE6M/hqdefault.jpg)](https://youtu.be/B8qarIAuE6M) 3 | 4 |

Create procedural rivers in unity 2d top down example map using Perlin worms algorithm. 5 | 6 | 7 |

Attribution: 8 | Made by Sunny Valley Studio 9 | -------------------------------------------------------------------------------- /Scripts/MapGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using UnityEngine; 6 | using UnityEngine.Tilemaps; 7 | 8 | public class MapGenerator : MonoBehaviour 9 | { 10 | public MapRenderer mapRenderer; 11 | public TileBase grassTile, waterTile, hillTile, snowTile, maxPosTile; 12 | public int mapSize; 13 | public NoiseSettings mapSettings; 14 | public float hillHeight = 0.5f, snowHeight = 0.6f, waterHeight = 0.4f; 15 | public float[,] noiseMap; 16 | 17 | private void Start() 18 | { 19 | noiseMap = new float[mapSize, mapSize]; 20 | PrepareMap(); 21 | } 22 | 23 | public void PrepareMap() 24 | { 25 | Debug.Log("Generating map"); 26 | mapRenderer.ClearMap(); 27 | 28 | for (int x = 0; x < mapSize; x++) 29 | { 30 | for (int y = 0; y < mapSize; y++) 31 | { 32 | var noise = NoiseHelper.SumNoise(x, y, mapSettings); 33 | noiseMap[x, y] = noise; 34 | if (noise > snowHeight) 35 | { 36 | mapRenderer.SetTileTo(x, y, snowTile); 37 | }else if(noise > hillHeight) 38 | { 39 | mapRenderer.SetTileTo(x, y, hillTile); 40 | }else if (noise < waterHeight) 41 | { 42 | mapRenderer.SetTileTo(x, y, waterTile); 43 | } 44 | else 45 | { 46 | mapRenderer.SetTileTo(x, y, grassTile); 47 | } 48 | 49 | } 50 | } 51 | } 52 | 53 | public void ShowMaximas() 54 | { 55 | var result = NoiseHelper.FindLocalMaxima(noiseMap); 56 | result = result.Where(pos => noiseMap[pos.x, pos.y] > snowHeight).OrderBy(pos => noiseMap[pos.x, pos.y]).Take(20).ToList(); 57 | foreach (var item in result) 58 | { 59 | mapRenderer.SetTileTo(item.x, item.y, maxPosTile); 60 | } 61 | } 62 | 63 | public void ShowMinimas() 64 | { 65 | var result = NoiseHelper.FindLocalMinima(noiseMap); 66 | result = result.Where(pos => noiseMap[pos.x, pos.y] < waterHeight).OrderBy(pos => noiseMap[pos.x, pos.y]).Take(20).ToList(); 67 | foreach (var item in result) 68 | { 69 | mapRenderer.SetTileTo(item.x, item.y, maxPosTile); 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Scripts/MapRenderer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | using UnityEngine.Tilemaps; 6 | 7 | public class MapRenderer : MonoBehaviour 8 | { 9 | public Tilemap map; 10 | 11 | public void ClearMap() 12 | { 13 | map.ClearAllTiles(); 14 | } 15 | 16 | public void SetTileTo(int x, int y, TileBase tiletype) 17 | { 18 | map.SetTile(map.WorldToCell(new Vector3(x, y, 0)), tiletype); 19 | } 20 | 21 | public void SetTileTo(Vector3 pos, TileBase tiletype) 22 | { 23 | map.SetTile(map.WorldToCell(pos), tiletype); 24 | } 25 | 26 | public Vector3Int GetCellposition(Vector3 pos) 27 | { 28 | return map.WorldToCell(pos); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Scripts/NoiseHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | public static class NoiseHelper 7 | { 8 | 9 | public static float SumNoise(float x, float y, NoiseSettings noiseSettings) 10 | { 11 | float amplitude = 1; 12 | float frequency = noiseSettings.startFrequency; 13 | float noiseSum = 0; 14 | float amplitudeSum = 0; 15 | for (int i = 0; i < noiseSettings.octaves; i++) 16 | { 17 | noiseSum += amplitude * Mathf.PerlinNoise(x * frequency, y * frequency); 18 | amplitudeSum += amplitude; 19 | amplitude *= noiseSettings.persistance; 20 | frequency *= 2; 21 | 22 | } 23 | return noiseSum / amplitudeSum; // set range back to 0-1 24 | 25 | } 26 | 27 | public static float RangeMap(float inputValue, float inMin, float inMax, float outMin, float outMax) 28 | { 29 | return outMin + (inputValue - inMin) * (outMax - outMin) / (inMax - inMin); 30 | } 31 | 32 | public static List FindLocalMaxima(float[,] noiseMap) 33 | { 34 | List maximas = new List(); 35 | for (int x = 0; x < noiseMap.GetLength(0); x++) 36 | { 37 | for (int y = 0; y < noiseMap.GetLength(1); y++) 38 | { 39 | var noiseVal = noiseMap[x, y]; 40 | if (CheckNeighbours(x, y, noiseMap, (neighbourNoise) => neighbourNoise > noiseVal)) 41 | { 42 | maximas.Add(new Vector2Int(x, y)); 43 | } 44 | 45 | } 46 | } 47 | return maximas; 48 | } 49 | 50 | public static List FindLocalMinima(float[,] noiseMap) 51 | { 52 | List minima = new List(); 53 | for (int x = 0; x < noiseMap.GetLength(0); x++) 54 | { 55 | for (int y = 0; y < noiseMap.GetLength(1); y++) 56 | { 57 | var noiseVal = noiseMap[x, y]; 58 | if (CheckNeighbours(x, y, noiseMap, (neighbourNoise) => neighbourNoise < noiseVal)) 59 | { 60 | minima.Add(new Vector2Int(x, y)); 61 | } 62 | 63 | } 64 | } 65 | return minima; 66 | } 67 | 68 | static List directions = new List 69 | { 70 | new Vector2Int( 0, 1), //N 71 | new Vector2Int( 1, 1), //NE 72 | new Vector2Int( 1, 0), //E 73 | new Vector2Int(-1, 1), //SE 74 | new Vector2Int(-1, 0), //S 75 | new Vector2Int(-1,-1), //SW 76 | new Vector2Int( 0,-1), //W 77 | new Vector2Int( 1,-1) //NW 78 | }; 79 | 80 | private static bool CheckNeighbours(int x, int y, float[,] noiseMap, Func failCondition) 81 | { 82 | foreach (var dir in directions) 83 | { 84 | var newPost = new Vector2Int(x + dir.x, y + dir.y); 85 | 86 | if (newPost.x < 0 || newPost.x >= noiseMap.GetLength(0) || newPost.y < 0 || newPost.y >= noiseMap.GetLength(1)) 87 | { 88 | continue; 89 | } 90 | 91 | if (failCondition(noiseMap[x + dir.x, y + dir.y])) 92 | { 93 | return false; 94 | } 95 | } 96 | return true; 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /Scripts/NoiseSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | [Serializable] 7 | public class NoiseSettings 8 | { 9 | [Min(1)] 10 | public int octaves = 3; 11 | [Min(0.001f)] 12 | public float startFrequency = 0.01f; 13 | [Min(0)] 14 | public float persistance = 0.5f; 15 | } 16 | -------------------------------------------------------------------------------- /Scripts/PerlinWorm.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using UnityEngine; 5 | 6 | public class PerlinWorm 7 | { 8 | private Vector2 currentDirection; 9 | private Vector2 currentPosition; 10 | private Vector2 convergancePoint; 11 | NoiseSettings noiseSettings; 12 | public bool moveToConvergancepoint = false; 13 | [Range(0.5f, 0.9f)] 14 | public float weight = 0.6f; 15 | 16 | public PerlinWorm(NoiseSettings noiseSettings, Vector2 startPosition, Vector2 convergancePoint) 17 | { 18 | currentDirection = Random.insideUnitCircle.normalized; 19 | this.noiseSettings = noiseSettings; 20 | this.currentPosition = startPosition; 21 | this.convergancePoint = convergancePoint; 22 | this.moveToConvergancepoint = true; 23 | } 24 | 25 | public PerlinWorm(NoiseSettings noiseSettings, Vector2 startPosition) 26 | { 27 | currentDirection = Random.insideUnitCircle.normalized; 28 | this.noiseSettings = noiseSettings; 29 | this.currentPosition = startPosition; 30 | this.moveToConvergancepoint = false; 31 | } 32 | 33 | public Vector2 MoveTowardsConvergancePoint() 34 | { 35 | Vector3 direction = GetPerlinNoiseDirection(); 36 | var directionToConvergancePoint = (this.convergancePoint - currentPosition).normalized; 37 | var endDirection = ((Vector2)direction * (1 - weight) + directionToConvergancePoint * weight).normalized; 38 | currentPosition += endDirection; 39 | return currentPosition; 40 | } 41 | 42 | public Vector2 Move() 43 | { 44 | Vector3 direction = GetPerlinNoiseDirection(); 45 | currentPosition += (Vector2)direction; 46 | return currentPosition; 47 | } 48 | 49 | private Vector3 GetPerlinNoiseDirection() 50 | { 51 | float noise = NoiseHelper.SumNoise(currentPosition.x, currentPosition.y, noiseSettings); //0-1 52 | float degrees = NoiseHelper.RangeMap(noise, 0, 1, -90, 90); 53 | currentDirection = (Quaternion.AngleAxis(degrees, Vector3.forward) * currentDirection).normalized; 54 | return currentDirection; 55 | } 56 | 57 | public List MoveLength(int length) 58 | { 59 | var list = new List(); 60 | foreach (var item in Enumerable.Range(0, length)) 61 | { 62 | if (moveToConvergancepoint) 63 | { 64 | var result = MoveTowardsConvergancePoint(); 65 | list.Add(result); 66 | if (Vector2.Distance(this.convergancePoint, result) < 1) 67 | { 68 | break; 69 | } 70 | } 71 | else 72 | { 73 | var result = Move(); 74 | list.Add(result); 75 | } 76 | 77 | 78 | } 79 | if (moveToConvergancepoint) 80 | { 81 | while (Vector2.Distance(this.convergancePoint, currentPosition) > 1) 82 | { 83 | weight = 0.9f; 84 | var result = MoveTowardsConvergancePoint(); 85 | list.Add(result); 86 | if (Vector2.Distance(this.convergancePoint, result) < 1) 87 | { 88 | break; 89 | } 90 | } 91 | } 92 | 93 | return list; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /Scripts/RiverGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using UnityEngine; 6 | 7 | public class RiverGenerator : MonoBehaviour 8 | { 9 | public MapGenerator mapGenerator; 10 | public NoiseSettings riverSettings; 11 | public Vector2 riverStartPosition; 12 | public int riverLength = 50; 13 | public bool bold = true; 14 | public bool converganceOn = true; 15 | 16 | public void GenerateRivers() 17 | { 18 | var result = NoiseHelper.FindLocalMaxima(mapGenerator.noiseMap); 19 | var toCreate = result.Where(pos => mapGenerator.noiseMap[pos.x, pos.y] > mapGenerator.snowHeight).OrderBy(a => Guid.NewGuid()).Take(5).ToList(); 20 | var waterMinimas = NoiseHelper.FindLocalMinima(mapGenerator.noiseMap); 21 | waterMinimas = waterMinimas.Where(pos => mapGenerator.noiseMap[pos.x, pos.y] < mapGenerator.waterHeight).OrderBy(pos => mapGenerator.noiseMap[pos.x, pos.y]).Take(20).ToList(); 22 | foreach (var item in toCreate) 23 | { 24 | //SetTileTo(item.x, item.y, maxPosTile); 25 | CreateRiver(item, waterMinimas); 26 | //return; 27 | } 28 | } 29 | 30 | private void CreateRiver(Vector2Int startPosition, List waterMinimas) 31 | { 32 | PerlinWorm worm; 33 | if (converganceOn) 34 | { 35 | var closestWaterPos = waterMinimas.OrderBy(pos => Vector2.Distance(pos, startPosition)).First(); 36 | worm = new PerlinWorm(riverSettings, startPosition, closestWaterPos); 37 | } 38 | else 39 | { 40 | worm = new PerlinWorm(riverSettings, startPosition); 41 | } 42 | 43 | var position = worm.MoveLength(riverLength); 44 | StartCoroutine(PlaceRiverTile(position)); 45 | } 46 | 47 | IEnumerator PlaceRiverTile(List positons) 48 | { 49 | foreach (var pos in positons) 50 | { 51 | var tilePos = mapGenerator.mapRenderer.GetCellposition(pos); 52 | if (tilePos.x < 0 || tilePos.x >= mapGenerator.mapSize || tilePos.y < 0 || tilePos.y >= mapGenerator.mapSize) 53 | break; 54 | mapGenerator.mapRenderer.SetTileTo(tilePos, mapGenerator.waterTile); 55 | if (bold && mapGenerator.noiseMap[tilePos.x, tilePos.y] < mapGenerator.hillHeight) 56 | { 57 | mapGenerator.mapRenderer.SetTileTo(tilePos + Vector3Int.right, mapGenerator.waterTile); 58 | mapGenerator.mapRenderer.SetTileTo(tilePos + Vector3Int.left, mapGenerator.waterTile); 59 | mapGenerator.mapRenderer.SetTileTo(tilePos + Vector3Int.up, mapGenerator.waterTile); 60 | mapGenerator.mapRenderer.SetTileTo(tilePos + Vector3Int.down, mapGenerator.waterTile); 61 | } 62 | yield return new WaitForSeconds(0.1f); 63 | } 64 | yield return null; 65 | } 66 | } 67 | --------------------------------------------------------------------------------