- Home /
Spawning at a random position away from the player
I want to spawn my enemies randomly around the map at a certain distance from my player. I guess I'm looking for something similar to Random.onUnitSphere but inverted so that I can get some x and z coordinates at a certain range. My y coordinate will come from raycasting, as I will be shooting a series of rays to determine if the randomly selected position is suitable to spawn on (is it walkable, is it level enough and free from collision etc.)
Does anyone have any idea how I can go about doing this?
Answer by Bunny83 · Aug 16, 2011 at 12:10 PM
You can use Random.insideUnitCircle which would be almost the same as using Random.onUnitSphere and just cancel out the y-part. When you normalize the Vector it will have a length of 1.0. Multiply it with your range and you got your point. This method have a little problem when insideUnitCircle or onUnitSphere returns 0,0,0 which is possible.
Or do it the traditional way: using trigonometry ;)
// C#
// get a random direction (360°) in radians
float angle = Random.Range(0.0f,Mathf.PI*2);
// create a vector with length 1.0
Vector3 V = new Vector3(Mathf.Sin(angle),0,Mathf.Cos(angle));
// scale it to the desired length
V *= Range;