Sorry, I'm not sure I understand the maths in that but I'm pretty sure the reflected vector shouldn't be calculated using x1,y1,z1.
Here's an attempt using a different method (probably a bit slower due to quite a few SQRs)but I'm not sure it's working as you want as the green cube doesn't seem to be in the right place.
Function sphere_line_intersection2 (x0#,y0#,z0#, x1#,y1#,z1#,cx#,cy#,cz#,r#)
;get ray vector and normalise
nx#=x1-x0
ny#=y1-y0
nz#=z1-z0
d#=1.0/Sqr(nx*nx+ny*ny+nz*nz)
nx=nx*d
ny=ny*d
nz=nz*d
;get vector from one point on the ray to the centre of the sphere
vx#=cx-x0
vy#=cy-y0
vz#=cz-z0
;dot product to find distance from point 0 to the point of the line closest to the centre of the sphere
d#=vx*nx+vy*ny+vz*nz
;is the point in front?
If d>0.0 Then
;find the coordinates of the closest point of the ray to the centre of the sphere
px#=x0+nx*d
py#=y0+ny*d
pz#=z0+nz*d
;find the distance from the centre of the sphere to the closest point on the ray
d#=Sqr((px-cx)^2+(py-cy)^2+(pz-cz)^2)
;does the ray intersect the sphere?
If d<=r Then
;use pythagoras to find 1/2 * the size of the chord (how much of the ray is within the sphere)
d#=Sqr(r*r-d*d)
;subtract that from the closest point (back towards point 0)
picked1(0)=px-nx*d
picked1(1)=py-ny*d
picked1(2)=pz-nz*d
;find the vector from the centre of the sphere to the point of intersection and normalise (the collision normal)
vx=picked1(0)-cx
vy=picked1(1)-cy
vz=picked1(2)-cz
d=1.0/Sqr(vx*vx+vy*vy+vz*vz)
vx=vx*d
vy=vy*d
vz=vz*d
;reflect the ray vector n using collision normal v
d=2.0*(vx*nx+vy*ny+vz*nz)
picked2(0)=nx-vx*d
picked2(1)=ny-vy*d
picked2(2)=nz-vz*d
Return 1
End If
End If
Return 0
End Function