function [t] = intersect(e,v,c,r) %Computes the intersection of a sphere and a parametrically %defined ray, given the center and radius of the sphere, the %ray originating point, and the ray direction. temp(1) = sum(v.^2); %a temp(2) = v(1)*(e(1)-c(1)) + v(2)*(e(2)-c(2)) + v(3)*(e(3)-c(3)); temp(2) = 2*temp(2); %b, and below, c. temp(3) = sum(e.^2) + sum(c.^2) - 2*(e(1)*c(1) + e(2)*c(2) + e(3)*c(3)) - r^2; %Now we plug into Descartes equation and find two t's. Among the %real positive roots, the smaller is the front of the sphere's intersection %with the ray, which is only a concern if the sphere is closest along that %ray. t(1) = (-temp(2) + sqrt(temp(2)^2 - 4*temp(1)*temp(3)))/(2*temp(1)); t(2) = (-temp(2) - sqrt(temp(2)^2 - 4*temp(1)*temp(3)))/(2*temp(1));