Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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));
 }
share|improve this question
1  
Well, it seems to be right. –  Notabene Jan 12 '11 at 19:39

1 Answer 1

up vote 4 down vote accepted

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;
share|improve this answer
    
@notabene - cross() and dot() are 3d matrix functions? or are they math for triangles? could I ask for those too :)? You see I'm porting it to a much dumber language... –  Jarvis Jan 12 '11 at 18:43
1  
@Jenko Yes float t is a Z value. And cross and dot are the algebraic functions. What language are you using. I'm sure that there is some kind of simple algebra library. –  Notabene Jan 12 '11 at 18:51
    
@notabene - Thank you! I'll try it out and let you know if it works ... :) –  Jarvis Jan 12 '11 at 19:06
1  
@Jenko - Yes you are always counting dot/cross product for 2 vectors. And good luck. –  Notabene Jan 12 '11 at 19:13
    
@notabene - what does aRay.org and aRay.dir do? the origin and the direction of the vector? how can I calculate these? –  Jarvis Jan 12 '11 at 19:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.