I'm stuck trying to make a simple ray sphere intersection test. I'm using this tutorial as my guide and taking code from there. As of now, I'm pretty sure I have the ray sorted out correctly. The way I'm testing my ray is by using the direction of the ray as the position of a cube, just to make sure it's in front of me.
cube.transform.position.x = Camera.main.ray.origin.x + Camera.main.ray.direction.x * 4;
cube.transform.position.y = Camera.main.ray.origin.y + Camera.main.ray.direction.y * 4;
cube.transform.position.z = Camera.main.ray.origin.z + Camera.main.ray.direction.z * 4;
So if I rotate the camera, the cube follows. So it's looking good.
The problem occurs with the actual intersection algorithm. Here are the steps I'm taking, I'll be very brief:
1) I subtract the sphere center with the ray origin:
L.x = entity.rigidbody.collider.center.x - ray.origin.x;
L.y = entity.rigidbody.collider.center.y - ray.origin.y;
L.z = entity.rigidbody.collider.center.z - ray.origin.z;
L.normalize();
2) I get the dot product of L and the ray direction:
const b = Mathf.dot(L, ray.direction);
3) And also the dot product of L with itself (I'm not sure if I'm doing this step right):
const c = Mathf.dot(L, L);
4) So now I can check if B is less than 0, which means it's behind the object. That's working very nicely.
L.x = entity.rigidbody.collider.center.x - ray.origin.x;
L.y = entity.rigidbody.collider.center.y - ray.origin.y;
L.z = entity.rigidbody.collider.center.z - ray.origin.z;
const b = Mathf.dot(L, ray.direction);
const c = Mathf.dot(L, L);
if (b < 0) return false;
Problem starts here
5) I now do this:
let d2 = (c * c) - (b * b);
6) ...and check if d2 > (entity.radius * entity.radius) and if it's greater: stop there by returning false. But it always passes, unless I don't normalize L and d2 ends up being a larger number and then it return false:
const radius2 = entity.rigidbody.collider.radius * entity.rigidbody.collider.radius;
if (d2 > radius2) return false;
but again, since I'm normalizing, it NEVER stops in that step. Which worries me.
7) I then do this:
let t1c = Math.sqrt(radius2 - d2);
...but it always returns a number in the range of 0.98, 0.97, if I'm standing still. But if I strafe left and right, the number lowers. If I rotate the camera, it makes no difference. Only if I strafe.
So I'm clearly doing something wrong and stopped there. Hopefully I made sense