3

I have a rectangle in 3d space (p1, p2, p3, p4) and when the mouse rolls over it I need to calculate the exact Z of the point on the rect, given the mouse coordinates (x, y).

Would a Ray-plane intersection find the Z of the intersecting point?


Edit: Would this one-liner work? .. it returns the t value for the intersection, apparently the Z value.

 float rayPlane(vector3D planepoint, vector3D normal, vector3D origin, vector3D direction){

     return -((origin-planepoint).dot(normal))/(direction.dot(normal));
 }
Pikalek
  • 12,372
  • 5
  • 43
  • 51
Robin Rodricks
  • 2,751
  • 3
  • 28
  • 52

1 Answers1

4

If you dont mind using your rect as two triangles, here is the code from my (working) raytracer:

//RAY-TRAINGLE test
Vec3f e1 = p2 - p1;
Vec3f e2 = p3 - p1;
Vec3f s1 = cross(aRay.dir, e2);

float divisor = dot(s1, e1);
if (divisor == 0.)
 return false; //not hit

float invDivisor = 1.f / divisor;

// Compute first barycentric coordinate
Vec3f d = aRay.org - p1;

float b1 = dot(d, s1) * invDivisor;
if (b1 < 0. || b1 > 1.)
 return false; // not hit

// Compute second barycentric coordinate
Vec3f s2 = cross(d, e1);
float b2 = dot(aRay.dir, s2) * invDivisor;
if (b2 < 0. || b1 + b2 > 1.)
 return false;

// Compute _t_ to intersection distance
float t = dot(e2, s2) * invDivisor; /// << HERE you go.
Vec3f intersection = aRay.org + t*aRay.dir;
Notabene
  • 6,068
  • 1
  • 32
  • 40