Convert two points to a ray?

I need to use sphere cast between two points to look for collisions.
But sphere cast doesn’t have a function to work between two points, it takes a start, a direction, and a distance. (Or a start and a ray, which is just the same data packaged differently.)

How can I make a quick conversion between these two? If I have start point and end point in 3D space, how to I change that end point into a direction and a distance?

Is there a function to generate a ray between two points, and a simple way to get the distance between the points?

I tried searching for this, but I get people being told to just use linecast instead. But I can’t use that here, unless there is some sort of sphere-lineCast I am unaware of.

i guess could do regular spherecast,
and then if hit distance is bigger than the distance to 2nd point, don’t count it as a collision?

Ray from 2 points:

var ray = new Ray(start, end - start);

(the constructor of ray will normalize direction for you)

So you could just say:

RaycastHit hit;
if(Physics.SphereCast(new Ray(start, end - start), radius, out hit, (end - start).magnitude))
{

}

Of course there is an overload that takes a start and direction vector:

RaycastHit hit;
if(Physics.SphereCast(start, radius, end - start, out hit, (end - start).magnitude))
{

}

Or you could also just create your own:

public static class PhysicsUtil
{
    public static bool SphereCast(Vector3 start, Vector3 end, float radius, out RaycastHit hit, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal)
    {
        return Physics.SphereCast(start, radius, end - start, out hit, (end - start).magnitude, layerMask, queryTriggerInteraction);
    }
}

(all code was written here in the wysiwyg of my browser… sorry if I typoed some)

2 Likes