I wrote some classes in Unity to calculate whether or not a ray intersects a plane or a sphere. We can represent rays parametrically by p(t) = p0 + td, where p0 is the ray origin and d the “delta vector” containing its length and direction. t is a scalar that can either be within [0,1] (as in the plane example) or [0,l], where l is the length of the ray (as in the sphere example).
Calculating whether there is an intersection and the point of intersection involves solving for t in these cases. It was a lot of fun!
Sphere intersection by ray code:
(Right click images and “View Image” to zoom in)
Cube intersection code:
Plane intersection by ray: