How to set the position of the sphere cast (Random.insideUnitSphere)?

I am trying to cast a Random.insideUnitSphere.

As I understand it, this call will return a random Vector3 within a sphere of 1 radius (which I multiply by whatever variable I set).

new Vector3 myPosition = Random.insideUnitSphere * someVariable;

But, how do I set the position of the sphere that I am casting? Can it only cast from the transform.position of the gameObject that contains the class from which the call is made?

I hope that I have explained it clearly. I’ve been stuck on this for several hours.

2 Answers

2

If you want to change the position of the “sphere” you simply have to add the offset vector, something along the lines:

Vector3 v  = Random.insideUnitSphere * 2f + new Vector3(4f, 0, 0);

Relative to the gameObject that the call is made from or world space?

Thank you for your replies. I will try to get this working, when I wake up.

This is what I had so far, still not quite there. The goal is for each sphere to spawn at a random location within the previous sphere.

public class Spheres : MonoBehaviour
{
	public float sphereDiameter;
	public GameObject sphereObject;
	
	float sphereRadius = sphereDiameter / 2;
	Vector3 spawnPosition;
	Vector3 newSpawnPosition;
	int sphereIndex = 0;
	
	void SpawnSphere()
	{
		if(sphereIndex == 0)
		{
			newSpawnPosition = Random.insideUnitSphere * sphereRadius;
			spawnPosition = newSpawnPosition;
		}
		else
		{
			newSpawnPosition = spawnPosition + Random.insideUnitSphere * sphereRadius;
		}
		
		GameObject sphere = Instantiate(spereObject, newSpawnPosition, Quaternian.Identity);
		sphere.gameObject.name = "Sphere" + sphereIndex.ToString();
		
		sphereIndex++;
	}
}