 # I am try to make a ray Sphere intersection function work for a post-processing effect in threejs but am stuck

I’ve been trying to add this post-processing (taken from sebastian lague video which I am trying to convert from unity to threejs) effect that when a ray hits the ocean on my mesh

(the blue) it is colored white (just like in his video

) ), and everywhere else the original color is returned. But for the life of me can’t seem to figure out the problem, I assume my ray origin or direction might be wrong but nothing seems to work, get an enitrely white screen instead of just the ‘ocean parts’ , Here’s the code that I pass to the ray Sphere intersection function and the function itself.

``````vec2 raySphere(vec3 centre, float radius, vec3 rayOrigin, vec3 rayDir) {
vec3 offset = rayOrigin - centre;
float a = 1.0; // set  to dot(rayDir, rayDir) instead of rayDir may not be normalized
float b = 2.0 * dot(offset, rayDir);
float c = dot(offset, offset) - radius * radius;

float discriminant = b*b-4.0*a*c;
// No intersection: discriminant < 0
// 1 intersection: discriminant == 0
// 2 intersection: discriminant > 0
if(discriminant > 0.0) {
float s = sqrt(discriminant);
float dstToSphereNear = max(0.0, (-b - s) / (2.0 * a));
float dstToSphereFar = (-b + s) / (2.0 * a);

if (dstToSphereFar >= 0.0) {
return vec2(dstToSphereNear, dstToSphereFar-dstToSphereNear);
}
}

return vec2(99999999, 0.0);
}

void main() {
float depth = readDepth(tDepth, vUv);
vec4 ro = inverse(modelMatrix) * vec4(cameraPosition, 1.0);
// position in object space
vec3 rd = normalize(position - ro.xyz);

vec3 oceanCentre = vec3(0.0, 0.0, 0.0);
float oceanRadius = 32.0;
vec2 hitInfo = raySphere(oceanCentre, oceanRadius, ro.xyz, rd);
float dstToOcean = hitInfo.x;
float dstThroughOcean = hitInfo.y;

vec3 rayOceanIntersectPos = ro.xyz + rd * dstToOcean - oceanCentre;

// dst that view ray travels through ocean (before hitting terrain / exiting ocean)
float oceanViewDepth = min(dstThroughOcean, depth - dstToOcean);
vec4 oceanCol;
float alpha;

if(oceanViewDepth > 0.0) {
gl_FragColor = vec4(vec3(1.0), .1);
}
gl_FragColor = texture2D(tDiffuse, vUv);
}
``````

If anyone can help point out where I might be messing up, that’d be much appreciated, or to some resources thanks!