How to get objects to spawn in according to rules
Hi I am experimenting with creating a procedural world(hope I am using that right) as in just creating a world with code. I am trying to get trees to spawn in randomly over the map, which they do perfectly fine. The problem is that I want a tree to NOT spawn if it detects another object other than the floor in the vicinity. I am not quite sure how to do this. I have some code in there that should work but for some reason it does not. I will post it here. Please help and much appreciated.
private void SpawnTree(Vector3 pos, GameObject spawn) { Vector3 position = pos; GameObject type = spawn; bool spawnIn = false; float radius = 500; int i = 0; Collider[] nearbyTrees = Physics.OverlapSphere(position, radius); while (i < nearbyTrees.Length) { if (nearbyTrees[i].tag != "Ground") { spawnIn = false; i = nearbyTrees.Length; } else { spawnIn = true; i++; } } if(spawnIn == true) { Instantiate(type, position, Quaternion.Euler(0.0f, Random.Range(0.0f, 360.0f), 0.0f)); spawnIn = false; } }
This is the snippet that looks for another object and then adds it to an array which then it goes through looking if it finds anything other than ground and then if at the end only ground was found for that position it spawns the tree. Then it calls the method again with another different random position on the map. It does this as many times as I tell it to spawn trees(which is a fixed variable at the top). However no matter how big I make the radius or how many trees I spawn in there are clipping trees that are too close to each other. Also I have it print the number of trees spawned and it always matches the number I told it to spawn in which is fine but at the same time like I said sometimes it shouldn't spawn in a tree. If anyone needs anything else please let me know.
Answer by tormentoarmagedoom · Apr 23, 2018 at 02:44 PM
Good day.
You should please create a prefab consisting of a empty gameobject with a script that detects close objects via OnTriggerStay() . If detects some other tree, change position. If not, instantiate a tree and then chenage position.
Bye!
I'm afraid I don't quite understand. I have the empty game-object that is how I create the world procedurally but OnTriggerStay() does not seem to be able to detect things close to it, only things that actually collide with it. Or do you mean if a tree is colliding with another tree move it, which would take place after the initial spawn in? (like pruning the forest after the initial spawn?)
Your answer
Follow this Question
Related Questions
[Solved] GI like lighting in procedural world 1 Answer
Example of Procedural Planet generation? 3 Answers
using several compilers, interpreter inside a game 0 Answers
unet synchroinze simple procedurally created map on clients 0 Answers
Best algorithm for large scale procedural level generation? 0 Answers