V

Avatar



Ray-Sphere intersection

After the creation of [We.are.in.Helsinki,3D] i came across a problemwhen using GL_SELECT opengl mode for intersections and picking. I got few complains that when picking a generator the application freezed. I had two options:  1. Make a simplified version of the generator’s spheres to render on the GL_SELECT mode. 2. Create a function that would tell me which object i clicked on using ray-sphere intersections.

I took option 2 and made an example in processing. It uses my own library, Vitamin. Its in the zipfile, make sure it is in the right place.

Download: http://www.pixelnerve.com/downloads/processing/intersectRaySphere.zip

Explanation:
First i already had my mouse position in 3D. Just had to convert it to world-space and put it in  the magic function that would tell me if the ray has hit anything, in this case a sphere. Magic function below:

// This function is part of the VRay class.
// Takes a point and a radius and returns number of hits
int intersectRaySphereHits( Vector3 center, float radius )
{
  // Solve quadratic equation
  float a = _direction.lengthSqr();
  if (a == 0.0)  return 0;
  float b = 2.0f * (_point.dot(_direction) - _direction.dot(center));
  Vector3 tempDiff = Vector3.sub( center, _point );
  float c = tempDiff.lengthSqr() - (radius*radius);
  float disc = b * b - 4 * a * c;
  if( disc < 0.0f )
    return 0;
  int numIntersections;
  if (disc == 0.0f)
    numIntersections = 1;
  else
    numIntersections = 2;
 
  return numIntersections;
}




,