I’m somewhat new to programming.
I’m trying to write a recursive function in c# in Unity3d that will generate objects at random vector2 coordinates. I want to make sure that each object is at least at a distance of “x” magnitude from any other object.
//Origin = Max Distance from Center of Screen
private Vector2 RecursPos(float origin) {
Vector2 thisObjectPosition = new Vector2(this.x, this.y);
//Run through object List<>
for (int i = 0; i < ObjectList.Count; i++) {
//Set Position of Object in Vector2 checkPos = new Vector2(ObjectList_.x, ObjectList*.y); //Check if Distance of thisObject and ObjectList < 2 then give new Location if (Vector2.Distance(checkPos, thisPos) < 2) { return RecursPos(origin); } }* I know I’m missing something but I can’t figure it out. I’ve been working on this for hours and at my wits end. Any help, even pointing me to a resource to learn how to do this would be greatly appreciated. Thank you!_
There’s really no reason to use recursive there. Recursive is very tricky and VERY rarely used. (Been programming games for about 10+ years and only ever had to use it once)
Here’s a much simpler way. It simply continues to randomize the point and check against the other objects as long as it’s too close. When it’s not close to any object, the function ends and returns the point it found.
//Origin = Max Distance from Center of Screen
private Vector2 GetPos(float origin) {
//do{ }while(); = continues to do a block of code while the while() condition is true
do {
//create random point
Vector2 thisPos = new Vector2(Random.Range(-origin, origin), Random.Range(-origin, origin));
//default to a success
bool success = true;
//loop through all objects
for (int i = 0; i < ObjectList.Count; i++) {
Vector2 checkPos = new Vector2(ObjectList[i].x, ObjectList[i].y);
//check the distance to each object
if (Vector2.Distance(checkPos, thisPos) < 2) {
//if it's too close to even just 1 object, success is false
success = false;
}
}
}while (!success);
//so while success if false, it will stay stuck in that loop, randomizing the position, and checking all objects
//when success stays true, then it can exit the loop and end the function.
return thisPos;
}