private void FindPathToWater(Cell cell, Direction direction, ref River river) { if (cell.Rivers.Contains(river)) { return; } // check if there is already a river on this tile if (cell.Rivers.Count > 0) { river.Intersections++; } river.AddCell(cell); // get neighbors var left = GetLeft(cell); var right = GetRight(cell); var top = GetTop(cell); var bottom = GetBottom(cell); float leftValue = int.MaxValue; float rightValue = int.MaxValue; float topValue = int.MaxValue; float bottomValue = int.MaxValue; // query height values of neighbors if (left.GetRiverNeighborCount(river) < 2 && !river.Cells.Contains(left)) { leftValue = left.HeightValue; } if (right.GetRiverNeighborCount(river) < 2 && !river.Cells.Contains(right)) { rightValue = right.HeightValue; } if (top.GetRiverNeighborCount(river) < 2 && !river.Cells.Contains(top)) { topValue = top.HeightValue; } if (bottom.GetRiverNeighborCount(river) < 2 && !river.Cells.Contains(bottom)) { bottomValue = bottom.HeightValue; } // if neighbor is existing river that is not this one, flow into it if (bottom.Rivers.Count == 0 && !bottom.Collidable) { bottomValue = 0; } if (top.Rivers.Count == 0 && !top.Collidable) { topValue = 0; } if (left.Rivers.Count == 0 && !left.Collidable) { leftValue = 0; } if (right.Rivers.Count == 0 && !right.Collidable) { rightValue = 0; } // override flow direction if a tile is significantly lower if (direction == Direction.Left) { if (Mathf.Abs(rightValue - leftValue) < 0.1f) { rightValue = int.MaxValue; } } if (direction == Direction.Right) { if (Mathf.Abs(rightValue - leftValue) < 0.1f) { leftValue = int.MaxValue; } } if (direction == Direction.Top) { if (Mathf.Abs(topValue - bottomValue) < 0.1f) { bottomValue = int.MaxValue; } } if (direction == Direction.Bottom) { if (Mathf.Abs(topValue - bottomValue) < 0.1f) { topValue = int.MaxValue; } } // find mininum var min = Mathf.Min(Mathf.Min(Mathf.Min(leftValue, rightValue), topValue), bottomValue); // if no minimum found - exit if (min == int.MaxValue) { return; } //Move to next neighbor if (min == leftValue) { if (left.Collidable) { if (river.CurrentDirection != Direction.Left) { river.TurnCount++; river.CurrentDirection = Direction.Left; } FindPathToWater(left, direction, ref river); } } else if (min == rightValue) { if (right.Collidable) { if (river.CurrentDirection != Direction.Right) { river.TurnCount++; river.CurrentDirection = Direction.Right; } FindPathToWater(right, direction, ref river); } } else if (min == bottomValue) { if (bottom.Collidable) { if (river.CurrentDirection != Direction.Bottom) { river.TurnCount++; river.CurrentDirection = Direction.Bottom; } FindPathToWater(bottom, direction, ref river); } } else if (min == topValue) { if (top.Collidable) { if (river.CurrentDirection != Direction.Top) { river.TurnCount++; river.CurrentDirection = Direction.Top; } FindPathToWater(top, direction, ref river); } } }