Advertisement Jump to content
Sign in to follow this  

Ray-cast onto plane

This topic is 3015 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to cast a ray from the position of a user's touch on a iOS device onto a plane on the XZ axis in OpenGL ES. I have code to build the ray points from the touch position and viewport size, and code to generate the inverse view*proj. Also, I have some code to calculate the position on the plane where it does intersect, but that part isn't working so well. Any help with it is much appreciated!

CGPoint p = [[touches anyObject] locationInView:self.view];
cml::vector4f r1(p.x / windowSize.width / windowSize.height, p.y, 0.0f, 1.0f);
cml::vector4f r2(p.x / windowSize.width, p.y / windowSize.height, 1.0f, 1.0f);

// unproject the ray points
cml::matrix44f_c invViewProj = orbitCam.viewMat * ((OpenGLView*)self.view).projMat;
invViewProj = cml::inverse(invViewProj);

r1 = invViewProj * r1;
r2 = invViewProj * r2;

cml::vector3f R1(r1[0], r1[1], r1[2]);
cml::vector3f R2(r2[0], r2[1], r2[2]);
cml::vector3f dir = cml::normalize(R2 - R1);

cml::vector3f V1(1.0f, 0.0f, 0.0f);
cml::vector3f V2(0.0f, 0.0f, 1.0f);
cml::vector3f V3 = cml::cross(V1, V2);

cml::vector3f vRotRay1(cml::dot(V1, R1 - V1), cml::dot(V2, R1 - V1), cml::dot(V3, R1 - V1));
cml::vector3f vRotRay2(cml::dot(V1, R2 - V1), cml::dot(V2, R2 - V1), cml::dot(V3, R2 - V1));

float percent = vRotRay1[2] / (vRotRay2[2] - vRotRay1[2]);
cml::vector3f intersect = vRotRay1 + (vRotRay1 - vRotRay2) * percent;

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!