Created
March 16, 2015 05:54
-
-
Save wwwtyro/beecc31d65d1004f5a9d to your computer and use it in GitHub Desktop.
GLSL ray-sphere intersection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float raySphereIntersect(vec3 r0, vec3 rd, vec3 s0, float sr) { | |
// - r0: ray origin | |
// - rd: normalized ray direction | |
// - s0: sphere center | |
// - sr: sphere radius | |
// - Returns distance from r0 to first intersecion with sphere, | |
// or -1.0 if no intersection. | |
float a = dot(rd, rd); | |
vec3 s0_r0 = r0 - s0; | |
float b = 2.0 * dot(rd, s0_r0); | |
float c = dot(s0_r0, s0_r0) - (sr * sr); | |
if (b*b - 4.0*a*c < 0.0) { | |
return -1.0; | |
} | |
return (-b - sqrt((b*b) - 4.0*a*c))/(2.0*a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not me, I'm using it for Love2D.