- Home /
Spawn Random Objects on a Sphere Surface
Hi all that my first Question on UnityAnswer :) My problem as i said before is spawn randomly objects on a sphere surface in movement. i have 2 script started one of them work but didnt spawn objects random the other one didnt work and is intended to spawn them randomly( i found the secondo one online and guys who posted it said it worked for them but for me no).
1-
public GameObject ObjectPrefab; public int NumberOfPrefab; //public float Scale; private bool first = true;
[ContextMenu("Create Points")]
void Update () {
if ((Network.peerType == NetworkPeerType.Client || Network.peerType == NetworkPeerType.Server) && first==true) {
var points = UniformPointsOnSphere (NumberOfPrefab, (float)(transform.localScale.x)); // Scale
for (var i=0; i<NumberOfPrefab; i++) {
var g = Instantiate (ObjectPrefab, transform.position + points [i], Quaternion.LookRotation(transform.position + points [i]-transform.position)*Quaternion.FromToRotation(Vector3.up, transform.forward)) as GameObject;
g.transform.parent = transform;
//print (i + " of " + NumberOfPrefab + "\n");
}
first=false;
//print ((float)(transform.localScale.x));
}
}
Vector3[] UniformPointsOnSphere(float N, float scale) {
var points = new List<Vector3>();
var i = Mathf.PI * (3 - Mathf.Sqrt(5));
var o = 2 / N;
for(var k=0; k<N; k++) {
var y = k * o - 1 + (o / 2);
var r = Mathf.Sqrt(1 - y*y);
var phi = k * i;
points.Add(new Vector3(Mathf.Cos(phi)*r, y, Mathf.Sin(phi)*r) * scale);
}
return points.ToArray();
}
2-
int numberOfRuins = 100; int ruinCount; float minOriginDistance = 1.0f; RaycastHit hit; public GameObject ObjectPrefab;
void Start(){
while (ruinCount < numberOfRuins){
// cast a random ray to see if we hit land
Vector3 randomVec = Random.onUnitSphere*(float)(transform.localScale.x);
if (Physics.Linecast(randomVec * 2, transform.position, out hit, 1<<8)){
if (hit.point.magnitude > minOriginDistance){
// we hit land!
var obj = Instantiate(ObjectPrefab, hit.point, Quaternion.identity)as GameObject;
obj.transform.LookAt(hit.point + randomVec);
ruinCount++;
}
}
}
}
can u guys help me to understand why the second one didnt work ? ty
I'm not sure enough of what you are doing for an answer, but I do spot a couple of strange things. First when you do the Raycast():
if (Physics.Linecast(randomVec * 2, transform.position, out hit, 1<<8)){
The position you are using (randomVec) only works if your object is at (0,0,0). If your sphere is at some place other than the origin, then you would need to do:
if (Physics.Linecast(transform.position + randomVec * 2, transform.position, out hit, 1<<8)){
This line is also a bit problematic (though not your issue):
Vector3 randomVec = Random.onUnitSphere*(float)(transform.localScale.x);
'localScale.x' is the diameter of a standard sphere, not the radius.