Ammo.js Closest Hit vs All Hits Raycast
In 3D physics simulations powered by Ammo.js—the JavaScript port of the Bullet physics engine—raycasting is a critical tool for detecting intersections along a line segment. This article outlines the functional differences between a closest hit raycast and an all hits raycast, detailing how they handle collision detection, their primary use cases, and their impact on performance.
Closest Hit Raycast
A closest hit raycast projects a ray from a starting point to an endpoint and identifies only the single, nearest rigid body that obstructs the path.
- Behavior: The physics engine calculates intersections along the ray but only returns data for the collision point closest to the ray’s origin. Any obstacles behind the first hit are ignored.
- Ammo.js Class:
Ammo.ClosestRayResultCallback. - Use Cases:
- Standard shooting mechanics: Determining the exact point where a bullet impacts the first wall or enemy in its path.
- Ground detection: Checking the distance from a character’s feet to the floor to keep them grounded.
- Line-of-sight checks: Determining if an NPC can see the player without any solid obstacles blocking the view.
All Hits Raycast
An all hits raycast projects a ray from a starting point to an endpoint and records every single rigid body that the ray intersects.
- Behavior: The ray does not stop at the first obstruction. It penetrates through all objects along its vector, collecting a list of all hit points, collision normals, and rigid bodies.
- Ammo.js Class:
Ammo.AllHitsRayResultCallback. - Use Cases:
- Penetrating weapons: Simulating railguns, lasers, or high-caliber ammunition that pierce through multiple walls or enemies.
- Sensor scanning: Detecting all objects within a specific directional line to gather environmental data.
- Audio propagation: Calculating how many walls a sound wave must pass through to determine how much the audio should be muffled.
Key Differences At a Glance
1. Returned Data
- Closest Hit: Returns a single result object containing one collision body, one collision point, and one normal vector.
- All Hits: Returns arrays of collision bodies, hit points, and normal vectors, ordered by distance from the ray’s origin.
2. Performance
- Closest Hit: Fast and computationally efficient. The engine can quickly discard potential hits that are further away than an already registered hit.
- All Hits: More resource-intensive. The engine must track, sort, and return multiple intersection points along the entire length of the ray.
3. Bullet Penetration
- Closest Hit: Stops logically at the first surface of contact.
- All Hits: Completely penetrates all overlapping and sequential physical bodies until it reaches the end of the specified ray length.