Function cast_local_ray

Source
pub fn cast_local_ray<G: ?Sized + SupportMap>(
    shape: &G,
    simplex: &mut VoronoiSimplex,
    ray: &Ray,
    max_time_of_impact: f32,
) -> Option<(f32, Vector<f32>)>
Expand description

Casts a ray against a shape using the GJK algorithm.

This function performs raycasting by testing a ray against a shape to find if and where the ray intersects the shape. It uses a specialized version of GJK that works with rays.

§What is Raycasting?

Raycasting shoots a ray (infinite line starting from a point in a direction) and finds where it first hits a shape. This is essential for:

  • Mouse picking in 3D scenes
  • Line-of-sight checks
  • Projectile collision detection
  • Laser/scanner simulations

§Parameters

  • shape: The shape to cast the ray against (must implement SupportMap)
  • simplex: A reusable simplex structure. Initialize with VoronoiSimplex::new().
  • ray: The ray to cast, containing an origin point and direction vector
  • max_time_of_impact: Maximum distance along the ray to check. The ray will be treated as a line segment of length max_time_of_impact * ray.dir.norm().

§Returns

  • Some((toi, normal)): If the ray hits the shape
    • toi: Time of impact - multiply by ray.dir.norm() to get the actual distance
    • normal: Surface normal at the hit point
  • None: If the ray doesn’t hit the shape within the maximum distance

§Example

use parry3d::shape::Ball;
use parry3d::query::{Ray, gjk::{cast_local_ray, VoronoiSimplex}};
use parry3d::math::{Point, Vector};

// Create a ball at the origin
let ball = Ball::new(1.0);

// Create a ray starting at (0, 0, -5) pointing toward +Z
let ray = Ray::new(
    Point::new(0.0, 0.0, -5.0),
    Vector::new(0.0, 0.0, 1.0)
);

let mut simplex = VoronoiSimplex::new();
if let Some((toi, normal)) = cast_local_ray(&ball, &mut simplex, &ray, f32::MAX) {
    let hit_point = ray.point_at(toi);
    println!("Ray hit at: {:?}", hit_point);
    println!("Surface normal: {:?}", normal);
    println!("Distance: {}", toi);
} else {
    println!("Ray missed the shape");
}

§Notes

  • The ray is specified in the local-space of the shape
  • The returned normal points outward from the shape
  • For normalized ray directions, toi equals the distance to the hit point
  • This function is typically called by higher-level raycasting APIs