I’m curious to know if there is a function that can be used to create a random position within a specific radius, but ignoring any positions within a second radius. I know there is the Random.insideUnitSphere, insideUnitCircle and onUnitSphere, but as far as I can tell, there are no additional options. The idea would be to create, say, 50 objects within a 200 unit radius, but make sure none of them are instantiated within the first 100 units. Something along those lines. Are there any built-in functions with c# to handle this sort of thing? Or would I be creating my own logic?
To illustrate, I’ve drawn up a basic image that should help get the idea across. I’ll keep working at it tonight, though. I have that irritating feeling that the answer is right in front of me
Start with the object at the centre, rotate by a random amount up to 360 degrees, then move it in local space by a random range between the inner and outer radii.
Moonjump,
I will check that out as well! I did manage to figure out valid code that - so far - does what I need. Though at this point, it does rely on the parent object being placed at the world center. I will work on a local coordinate system for objects that aren’t located at that position.
Here is the code as it stands:
using UnityEngine;
using System.Collections;
//Attach this script to an empty gameobject at position 0, 0, 0 in the game world.
public class spawnRadii : MonoBehaviour {
public float nullRadius = 10f; //do not spawn anything within this radius.
public float spawnRadius = 20f; //maximum spawning range.
public int numCopies = 50; //number of copies to make of the prefab
public GameObject prefab; //the game object to instantiate.
void Start() {
//Create counter variable i. Create random vector2 within the spawn radius.
int i = 0;
while (i < numCopies) {
Vector2 vRad1 = Random.insideUnitCircle * spawnRadius;
float fDist = Vector2.Distance(vRad1, transform.localPosition);
//Check to see if the distance between vRad1 and the parent location
//is greater than the nullRadius (no-spawn area).
if(fDist >= nullRadius) {
Object copy;
copy = Instantiate(prefab, new Vector3(vRad1.x, 0f, vRad1.y), Quaternion.identity);
copy.name = "Instanced Object " + i.ToString();
i++; //increase the counter since we have created an object within a valid position.
}
}
}
}
On a secondary note, I just realized this was mistakenly posted under Unity Support. I’d like to request that this thread be moved to the Scripting area of the forums, please.