- Home /
Raycasting onto a sphere
Hi,
I'm attempting to spawn objects on a random point on a sphere. To get this point, I am calling Random.onUnitSphere
and multiplying that around 70 to make sure it's outside of the sphere. My sphere is located in the centre of the world so, I then call Physics.Raycast(randomSpherePoint, Vector3.zero, out hit)
. However, this never seems to be hitting anything and debug lines do not get drawn either. I have made sure that my sphere has a collider, too.
This is my full code:
for (int i = 0; i < 10; i++)
{
Vector3 randomSpherePoint = Random.onUnitSphere * 70;
RaycastHit hit;
Debug.DrawRay(randomSpherePoint, Vector3.zero, Color.white, 120);
if (Physics.Raycast(randomSpherePoint, Vector3.zero, out hit))
{
print("HIT!");
Instantiate(astroid, hit.transform);
}
}
Answer by Bunny83 · Apr 15, 2018 at 04:46 AM
A Raycast takes a start position in worldspace and a direction vector. You pass Vector3.zero as direction which is no direction at all. To get the direction vector from your point to the origin it's actually just the inverse of the position
if (Physics.Raycast(randomSpherePoint, - randomSpherePoint, out hit))
If the sphere is not located at (0,0,0) but at some "center" you would have to do:
if (Physics.Raycast(center + randomSpherePoint, center - randomSpherePoint, out hit))
However if you have an actual target point you may want to use a LineCast instead. The LineCast actually expects two worldspace points, a start and an end point.
@Bunny83 Thanks! Quick question, my casts seem to be intersecting at the centre as shown: https://i.imgur.com/0qlyRdZ.png
Whereas I want them to hit the green mesh. $$anonymous$$esh has a collider, and casts are made after the mesh is made, so I'm not sure why it's not hitting my mesh.
Well, do you have a $$anonymous$$eshCollider on that object? Raycast and LineCast can only hit colliders, not renderers.
@Bunny83 Yeah, it definitely has a collider, as shown here:
https://i.imgur.com/bp8wGZw.png