Vector notation for use in ray-sphere intersection

Started by poo2thegeek, January 05, 2014, 09:46:21

Previous topic - Next topic

poo2thegeek

I need to find out if a ray intersects an object. The object is technically a cube, but  sphere can suffice as I believe ray-sphere intersection is more efficient than ray-cube intersection (also, i cannot find any good info about ray-cube intersection).
I have got most of the maths needed from the Wikipedia page 'Lineâ€"sphere_intersection' 
( http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection )

But some of the stuff on the page doesn't seem to make much sense. For example, I can understand the first bit on the page that states taking the magnitude of (x-c)^2 = r^2, but later on the page tries to square raw vectors. For example, the very last bit of math is:
(o-c)^2 + r^2...
But o and c are vectors, so there is no way to square them is there? Unless I'm missing something else out of the page...
Thanks for any help explaining what I've done wrong!


quew8

Well r is the radius of the circle which makes it a plain old scalar. If you look carefully it is actually ( l . ( o - c ) ) ^ 2 (where . is the dot product) so that is also a scalar squared. If you don't understand any of the algebra, I would be happy to go through it with you (just ask) but I get the impression that your vector maths are a bit weak in general. If that's not the case I'm sorry, but if it is then I would recommend having a read of this: http://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/. It's where I learnt everything I know on the subject.

poo2thegeek

Ah I figured it out myself eventually, thanks still for the help.
I understood it all. My only problem was the power of two, I didn't see the part on the page that stated this to be a dot product. I assumed it meant to square a vector, something you can't do.
For anyone who ever needs this in future, here was my final code:

public static boolean rayIntersectsSphere(Vector3f sphereC, float radius, 
			Vector3f ray, Vector3f pos){
		float underrt = (square(dot(ray,minus(pos,sphereC))))-dot(minus(pos,sphereC),minus(pos,sphereC)) + square(radius);
		if(underrt<0) return false;
		return true;
	}