Skip to content

Instantly share code, notes, and snippets.

@wwwtyro
Created March 16, 2015 05:54
Show Gist options
  • Save wwwtyro/beecc31d65d1004f5a9d to your computer and use it in GitHub Desktop.
Save wwwtyro/beecc31d65d1004f5a9d to your computer and use it in GitHub Desktop.
GLSL ray-sphere intersection
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);
}
@jon-grangien
Copy link

Haha what the hell are you mad about upload your own function

@parker1911
Copy link

It worked for me just fine.

@GeraKuznetsov
Copy link

GeraKuznetsov commented Jul 27, 2019

IT DOESNT FUCKING WORK FUCK YOU

I too hate it when i steal other people's code but I am to stupid to figure out how to actually use it.

Joking aside, I made a small modification to return both intersection points:

vec2 raySphereIntersect(vec3 r0, vec3 rd, vec3 s0, float sr) {
    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);
	float disc = b * b - 4.0 * a* c;
    if (disc < 0.0) {
        return vec2(-1.0, -1.0);
    }else{
		return vec2(-b - sqrt(disc), -b + sqrt(disc)) / (2.0 * a);
	}
}```

@Broxxar
Copy link

Broxxar commented Aug 10, 2019

IT DOESNT FUCKING WORK FUCK YOU

Literally worked perfectly without any major changes. Imagine being this much of a tool.
raySphereIntersect

Thanks for the snippet OP!

@Ap0thecary
Copy link

IT DOESNT FUCKING WORK FUCK YOU

Imagine not having the problem solving skills to fix it if it didn't.

Literally worked perfectly without any major changes. Imagine being this much of a tool.
raySphereIntersect

Thanks for the snippet OP!

Looks super cool, I can't wait to try this out

@brandonhs
Copy link

brandonhs commented Mar 12, 2021

IT DOESNT FUCKING WORK FUCK YOU

M yes, I too hate it when I copy someone's code and I don't even know how to use, so I then go harrass the creator. /s

With that out of the way, the snippet works fine so thank you OP

@grigoryoskin
Copy link

In your comment it says rd: normalized ray direction, but then you compute dot(rd, rd) which is always one. So either rd should not be normalized or your code is doing unnecessary operations.

@stuw-u
Copy link

stuw-u commented Aug 5, 2022

lol are we all using this for a shader in unity

@RGBProductions
Copy link

lol are we all using this for a shader in unity

Not me, I'm using it for Love2D.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment