Creating a Ray for a Click Location
From C4 Engine Wiki
This code snippet demonstrates how to turn (x, y) screen coordinates into a ray that can be traced through the world.
void GetWorldRayFromClick(const Camera *camera, const Point& p, Ray *ray) { // Get the viewport rect for the camera. const Rect& viewRect = camera->GetObject()->GetViewRect(); // Normalize the click coordinates. float x = p.x / (float) viewRect.Width(); float y = p.y / (float) viewRect.Height(); // Cast a local ray from the camera. camera->CastRay(x, y, ray); // Transform the ray into world space. const Transform4D& cameraTransform = camera->GetNodeTransform(); ray->origin = cameraTransform * ray->origin; ray->direction = (cameraTransform * ray->direction).Normalize(); // Set the rest of the ray fields. ray->radius = 0.0F; ray->tmin = 0.0F; ray->tmax = 100.0F; // Set to max distance ray will go. }
