Need help trying to populate objects on a sphere randomly

So what I want to do is spawn a prefab that is a hill randomly on a sphere, representing a planet. Here’s what im trying to do so far:

  1. Get random points on the surface of the planet.
public GameObject hill;
	int numHills;
	
	public Transform other;
	float radius; 
	float angle = 180.0f;

public Vector3 GetPointOnUnitSphereCap(Quaternion targetDirection, float angle)
	{
	    float angleInRad = Random.Range(0.0f,angle) * Mathf.Deg2Rad;
    	Vector3 PointOnCircle = (Random.insideUnitCircle.normalized)*Mathf.Sin(angleInRad);
    	Vector3 V = new Vector3(PointOnCircle.x,PointOnCircle.y,Mathf.Cos(angleInRad));
    	return targetDirection*V;
	}

I got this code from someone doing a similar thing

  1. Cast a ray from that random point to the sphere and get the normal of that point on the surface of the sphere. Using that normal, set the rotation of the hill to that normal.
void Start()
	{
		radius = transform.localScale.x * ((SphereCollider)collider).radius;
		numHills = 50;
		for(int i=0;i<numHills;i++)
		{
			Vector3 V = GetPointOnUnitSphereCap(transform.rotation,angle) * radius;
			V = other.position + V;
			Vector3 direction = other.transform.position - V;
			RaycastHit hit;
			//Debug.Log(V);
			if(Physics.Raycast(V, direction, out hit))
			{
				Vector3 incomingVec = hit.point - hill.transform.position;
				Vector3 reflect = Vector3.Reflect(V, hit.normal);
				//float ang = Vector3.Angle(incomingVec, reflect);
				//Vector3 fin = new Vector3(0, ang, 0);
				Instantiate(hill, V, Quaternion.Euler(reflect));
				//Debug.DrawLine(V, hit.point, Color.red );
			}
			//Debug.Log(GetPointOnUnitSphereCap(transform.rotation,angle));
		}
	}

seems not to be working as intended. the rotations is what is messed up

You are massively overcomplicating this for yourself :wink:
In pseudo-code:

// Position
Vector3 randomPointOnUnitSphere = Random.onUnitSphere;
hill.transform.position = planet.transform.position + randomPointOnUnitSphere;

// Rotation
Vector3 randomTangent = Random.onUnitSphere;
Vector3.OrthoNormalize(ref randomPointOnUnitSphere, ref randomTangent);
hill.transform.rotation = Quaternion.LookRotation(randomTangent, randomPointOnUnitSphere);
1 Like