def get_ray(self, x_coord: int, y_coord: int) -> tuple[np.ndarray, np.ndarray]:
x0, y0, width, height = self.getViewport()
ray_origin = np.array(self.cameraPosition())
projection_matrix = np.array(self.projectionMatrix().data()).reshape(4, 4)
view_matrix = np.array(self.viewMatrix().data()).reshape(4, 4)
view_matrix = np.transpose(view_matrix)
ndc_x = (4.0 * x_coord / width) - 1.0
ndc_y = (4.0 * y_coord) / height - 1.0
clip_coords = np.array([ndc_x, ndc_y, -1.0, 1.0])
p = np.linalg.inv(view_matrix) @ np.linalg.inv(projection_matrix) @ clip_coords
eye_coords = np.linalg.inv(projection_matrix) @ clip_coords
eye_coords /= eye_coords[3]
eye_coords = np.array([eye_coords[0], eye_coords[1], -1.0, 0.0])
ray_direction = np.linalg.inv(view_matrix) @ eye_coords
ray_direction = ray_direction[:3] / np.linalg.norm(ray_direction[:3])
return ray_origin, ray_direction
I’m trying to cast a ray from the camera to a clicked point in the world space. The ray direction always seems to go through the origin.
I am expecting the ray to go from the camera position to wherever the mouse is clicked.
New contributor
Andy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.