- Home /
Randomly create cubes on the surface of a sphere
I have a sphere. I want to hit it in random locations on the surface, and then mark each hit with a cube (to be replaced with an actual art asset later, obviously). How do I do this? I'm not having much luck, as my raycast-fu is weak. Here are the relevant bits of a script that's attached to the sphere:
var currentRuinsNumber = 0; var randomRuinsVector : Vector3;
// Find places for ruins while (currentRuinsNumber < numberOfRuins) { randomVector = Vector3(Random.Range(-1.0, 1.1), Random.Range(-1.0, 1.1), Random.Range(-1.0, 1.1) );
var ray : Ray = Ray(Vector3.zero, randomRuinsVector);
var hit : RaycastHit;
if (collider.Raycast(ray, hit, 100.0))
{
Debug.DrawLine (ray.origin, hit.point);
// put a cube here
}
currentRuinsNumber++;
}
Answer by Sladuuch · Feb 13, 2010 at 03:51 AM
You guys were right! I found some help elsewhere too and here's what works for me:
var numberOfRuins : int;
var ruinCount : int;
var minOriginDistance : float = 1.0;
var hit : RaycastHit;
while (ruinCount < numberOfRuins)
{
// cast a random ray to see if we hit land
randomVec = Random.onUnitSphere;
if (Physics.Linecast(randomVec * 2, Vector3.zero, hit, 1 << 8))
{
if (hit.point.magnitude > minOriginDistance)
{
// we hit land!
obj = Instantiate(ruinPrefab, hit.point, Quaternion.identity);
obj.transform.LookAt(hit.point + randomVec);
ruinCount++;
}
}
}
Answer by Ryuuguu · Feb 12, 2010 at 08:45 AM
If your just trying to get a random point on a sphere then there is a builtin function for that. code straight from docs.
rigidbody.velocity = Random.onUnitSphere * 10;
cheers, Grant
Additionally, if the shape isn't actually a perfect sphere and raycasting is needed, Random.onUnitSphere is still better to use for the randomVector that the raycast is based on.
Answer by Simon Wittber · Feb 08, 2011 at 02:21 AM
This will do exactly what you require. http://entitycrisis.blogspot.com/2011/02/uniform-points-on-sphere.html
Your answer
Follow this Question
Related Questions
Broadcast Message using RaycastAll 1 Answer
Making a shotgun 3 Answers
Generate a random direction within min and max angles 2 Answers