Hi, I came up with a problem I am trying to solve, for last couple of days. I am trying to create procedurally map based on nodes. Here is my problem They Are: 1. Overlapping 2. Too close to each other Here is a code of transforming them: Code (CSharp): public static Vector3 RndCircle(float radius) { float angle = Random.Range(-Mathf.PI, Mathf.PI); float x = Mathf.Cos(angle) * radius; float y = Mathf.Sin(angle) * radius; return new Vector3(x, y, 0); } void TransformSubNodes(GameObject parent) { for(int i = 0; i < parent.transform.childCount; i++) { parent.transform.GetChild(i).transform.position = parent.transform.position + RndCircle(5f); } ConnectSubNodes(parent); } I don't have any idea how to fix it. If someone could point me at some direction, I will be really thankful.
You could consider starting with a grid, where each section is only allowed to be occupied by a single node. Every time you add a depth, the next nodes go into adjecent sections that are unoccupied. For more randomness you could add random position offsets to the nodes. Just make sure that if each grid-section is 1x1, your maximum random offset is between 0 and 0.5 (assuming the node starts in the middle of the section) so they dont end up overlapping.
In any case, my Script order: SpawnMasterNode(int SubNodes) <- This Create the first node at (0,0) SubSubNode(int depth, int ammount) <- This Create a next depth with ammount per depth SpawnSubNode(GameObject parent, int ammount, int depth) <- spawn a sub node at position (0,0) times ammount (int depth is just for name) TransformSubNodes(GameObject parent) <- This transform a node 5f away from parent in a random place around parent ConnectSubNodes(GameObject parent) <- This one draw line between parent and its children List<GameObject> placed <- this is list of all spawned nodes Ok, I followed your advice, every node is on 1x1 position now, the yellow Circle contains two nodes (witch ok, I can destroy or move), but... the red Circle is what I want to fix to be like a green Circle the lines to not overlap each other. So that is the problem that I cannot pass, and I have not even close idea how to fix it.
The result you have shouldn't happen with the process i described. The step you seem to be missing in your latest process (from what i understand), is creating the grid (2d array). The grid is essential so the program can 'remember' the positions of each node in correlation to eachother. It seems you spawn the subnode in a 'random place'. If you use the 2d array, and the process i described, no place is fully random. Perhaps a step by step guide will clarify my earlier response: Create a 2d or 3d array that can house all the nodes you will need Create a node in the 2d array (first node is concidered master or root node) Get all available positions around this node from the 2d array (get node neighbours) Check to see which positions are available, ergo, do NOT yet have an active node in them Spawn subnodes within the array in any of the available neighbouring positions Repeat step 2 - 5 as many times as you would like and as long as there are positions available in the 2d array. This guide just sets up your nodes in a way they will never overlap or cross. The rest seems to be working already (lines between nodes etc...) so you should be fine. You can use the picture in my earlier response for visual support. Hope it helps.
as you said, I have already 1 & 2. "placed" is the array of all nodes (including master) as GameObject witch i can take .transform.position from it 3. i have created a FindLocations function that adds all possible Vector3 arround current node Code (CSharp): public List<Vector3> pLocations = new List<Vector3>(); //list of all possible locations void FindLocations(GameObject This) { pLocations.Clear(); for(int i = 1; i < 91; i++) { if(!pLocations.Contains(Loc(This.transform.position, i))) pLocations.Add(Loc(This.transform.position, i)); } } Vector3 Loc(Vector3 center, int multiply) { float radius = 5f; float angle = multiply * 4; float a = angle / 180 * Mathf.PI; int x = Mathf.RoundToInt(Mathf.Cos(a) * radius); int y = Mathf.RoundToInt(Mathf.Sin(a) * radius); return new Vector3(x + center.x, y + center.y, 0); } 4 & 5. Spawn Node on position and Remove it from array Code (CSharp): void CreateNode() { int rnd = Random.Range(0, pLocations.Count); Vector3 pos = pLocations[rnd]; GameObject go = Instantiate(nodeObj, pos, Quaternion.identity); pLocations.Remove(pos); if (go.transform.parent != null) DrawConnection(go); } i was thought about getting an angle between parent and parent.parent of current object then place it with random offset, eg. float angle = Vector3.Angle(parent, parent.parent) so this object, transform.position = Random.Range(angle - 5f, angle + 5f); but, that does not work as suppose to. so whatever I tried I end up with: A: Too close or overlapping (so i fixed it with Vector3.Distance) B: They are crossing the lines (and that is my biggest issue)
Here is the enitre code: https://hastebin.com/cazufihuge.cs using: attach this script to empty game object Node List = leave empty Node Obj = place any GameObject as a node Mat = material for line renderer Depth = ...Depth... how deep children will be created Ammount = Ammount of children per depth Rest of it, leave empty (seed is for generating the same level all the time, empty seed will randomise it)
Its messy, ugly and unoptimized. Also, there is a mistake in there (it might be the random we roll, there is a comment there saying we should 'keep score', but im not sure). Sorry, but i have no more time now to work on this today since i have my own stuff to do. I hope it will help you figure out one way you can achieve what you wish to achieve. Feel free to ask questions offcourse. All you have to do to check it out is add this script to an object in your scene and add an object to the nodeObj field in the inspector then hit play. Code (CSharp): using System.Collections.Generic; using UnityEngine; public class Map : MonoBehaviour { [SerializeField] private GameObject nodeObj; [SerializeField] private int gridSizeX = 64; [SerializeField] private int gridSizeY = 64; private Node[,] nodeGrid; private List<Node> finishedNodes; private class Node { public int x { get; set; } public int y { get; set; } public bool hasParent { get; set; } public Vector2Int parentPosition { get; set; } } // Execution pipeline: private void Start() { finishedNodes = new List<Node>(); InitGrid(); // ====================================================================================================================== // THE FOLLOWING CODE IN THIS METHOD (Start()) YOU CAN CUSTOMIZE TO MANIPULATE THE RESULT, SO YOU CAN GET WHAT YOU WANT // THIS IS A SIMPLE EXAMPLE TO SHOW YOU WHAT IT CAN DO: // ====================================================================================================================== // Master node: Node masterNode = GetAndAddNodeToGrid((int)(gridSizeX * 0.5f), (int)(gridSizeY * 0.5f)); // The following code splits, and can be modified to List<Node> split0 = GetAndAddNodeSplit(masterNode, 2); // Fractal typed explicitly, you could create a function that can do this indefinetly: foreach (Node n0 in split0) { List<Node> splits0 = GetAndAddNodeSplit(n0, 2); foreach (Node n1 in splits0) { List<Node> splits1 = GetAndAddNodeSplit(n1, 2); foreach (Node n2 in splits1) { List<Node> splits2 = GetAndAddNodeSplit(n2, 2); } } } // Always call this last, as this takes all data and actually creates the gameobjects in the scene: PrintNodeObjects(); } // Custom methods: private void InitGrid() { // Init grid with null values: nodeGrid = new Node[gridSizeX, gridSizeY]; } private List<Vector2Int> GetViablePerpendicularNeighbourPositions(Node _node) { List<Vector2Int> viableNeighbourPositions = new List<Vector2Int>(); if (_node.x - 1 >= 0) // Bound check if (nodeGrid[_node.x - 1, _node.y] == null) // Check for position availability viableNeighbourPositions.Add(new Vector2Int(_node.x - 1, _node.y)); // Add to list if (_node.x + 1 < gridSizeX - 1) if (nodeGrid[_node.x + 1, _node.y] == null) viableNeighbourPositions.Add(new Vector2Int(_node.x + 1, _node.y)); if (_node.y - 1 >= 0) if (nodeGrid[_node.x, _node.y - 1] == null) viableNeighbourPositions.Add(new Vector2Int(_node.x, _node.y - 1)); if (_node.y + 1 < gridSizeY - 1) if (nodeGrid[_node.x, _node.y + 1] == null) viableNeighbourPositions.Add(new Vector2Int(_node.x, _node.y + 1)); return viableNeighbourPositions; } private Node GetAndAddNodeToGrid(int _x, int _y, Vector2Int parentPosition = default) { Node newNode = new Node() { x = _x, y = _y }; nodeGrid[_x, _y] = newNode; // If there is a parentNode, save its position in the current node: if (parentPosition != default) { nodeGrid[_x, _y].hasParent = true; nodeGrid[_x, _y].parentPosition = new Vector2Int(parentPosition.x, parentPosition.y); } finishedNodes.Add(newNode); return newNode; } private List<Node> GetAndAddNodeSplit(Node node, int splitCount) { List<Vector2Int> nodeNeighbours = GetViablePerpendicularNeighbourPositions(node); List<Node> nodeSplits = new List<Node>(); for (int i = 0; i < splitCount; i++) { // Atm completely random, perhaps good idea to keep score so we dont roll the same random twice: int rand = Random.Range(0, nodeNeighbours.Count); Node newNode = GetAndAddNodeToGrid(nodeNeighbours[rand].x, nodeNeighbours[rand].y, new Vector2Int(node.x, node.y)); nodeSplits.Add(newNode); } return nodeSplits; } private void PrintNodeObjects() { foreach (Node n in finishedNodes) { GameObject node = Instantiate(nodeObj); node.transform.position = new Vector2(n.x, n.y); if (n.hasParent) { LineRenderer lr = node.AddComponent<LineRenderer>(); lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.SetPosition(0, new Vector3(n.x, n.y)); lr.SetPosition(1, new Vector3(n.parentPosition.x, n.parentPosition.y)); } } } }
I managed to make it work, it's slow, so I am highly NOT recommended this for mobile games: https://mega.nz/#!zsdFlK7R!2Ek_HrenkVOsvzHP__mrY2eUOf03SEdV2lcuCdwXMX8 NodeObj = use this as node GameObject LineMaterial = material that will be used for LineRenderer Depth = How many "children" are going to be from first node It's not used: "Ammount" Ammount = How many nodes are going to be created for each depth if you want to use it edit line 56 instead of: Code (CSharp): for(int i = 0; i < id * 4 * d; i++){ use: Code (CSharp): for(int i = 0; i < Ammount; i++){ I hope i helped you.