Raycasting

IntermediateProgrammer

Raycasting traces an invisible line through the scene to find intersecting colliders. This is useful, for example, to check which objects are in a gun's line of fire, or are under the mouse cursor when the user clicks.

Note

Raycasting uses colliders to calculate intersections. It ignores entities that have no collider component. For more information, see Colliders.

To use a raycast, in the current Simulation, use Simulation.Raycast.

For an example of raycasting, see the Physics Sample project included with Xenko.

Example code

This code sends a raycast from the mouse's screen position:

  1. public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation)
  2. {
  3. Matrix invViewProj = Matrix.Invert(camera.ViewProjectionMatrix);
  4. // Reconstruct the projection-space position in the (-1, +1) range.
  5. // Don't forget that Y is down in screen coordinates, but up in projection space
  6. Vector3 sPos;
  7. sPos.X = screenPos.X * 2f - 1f;
  8. sPos.Y = 1f - screenPos.Y * 2f;
  9. // Compute the near (start) point for the raycast
  10. // It's assumed to have the same projection space (x,y) coordinates and z = 0 (lying on the near plane)
  11. // We need to unproject it to world space
  12. sPos.Z = 0f;
  13. var vectorNear = Vector3.Transform(sPos, invViewProj);
  14. vectorNear /= vectorNear.W;
  15. // Compute the far (end) point for the raycast
  16. // It's assumed to have the same projection space (x,y) coordinates and z = 1 (lying on the far plane)
  17. // We need to unproject it to world space
  18. sPos.Z = 1f;
  19. var vectorFar = Vector3.Transform(sPos, invViewProj);
  20. vectorFar /= vectorFar.W;
  21. // Raycast from the point on the near plane to the point on the far plane and get the collision result
  22. var result = simulation.Raycast(vectorNear.XYZ(), vectorFar.XYZ());
  23. return result.Succeeded;
  24. }

See also