Contact Test vs Raycast in Ammo.js
This article explains the fundamental differences between a contact test and a standard raycast in the ammo.js physics engine. It explores how each method works, their primary use cases, and how to choose the right collision detection approach for your WebGL or 3D applications.
What is a Raycast in Ammo.js?
A raycast projects an imaginary, infinitely thin line from a starting point (vector A) to an ending point (vector B) through the physics world. The physics engine calculates whether this line intersects with any collision shapes along its path.
When a raycast hits an object, it returns detailed information, including: * The exact coordinates of the intersection point. * The normal vector of the surface that was hit. * The specific collision object that was intersected.
Common Use Cases for Raycasting
- Shooting mechanics: Simulating bullet trajectories in shooter games.
- Line of sight: Checking if an enemy AI can see the player without obstacles in the way.
- Ground detection: Testing if a character controller is currently standing on a surface.
- Object picking: Determining which 3D object a user clicked on the screen.
What is a Contact Test in Ammo.js?
A contact test (often implemented via contactTest or
contactPairTest) evaluates whether a specific 3D collision
shape (such as a sphere, box, or capsule) is overlapping or touching
other physical objects in the world.
Instead of projecting a 1D line, a contact test checks the volume of a 3D geometry against the geometry of other physical bodies. It returns a list of contact manifolds, which detail how deeply the shapes are penetrating each other and the specific points of contact.
Common Use Cases for Contact Tests
- Trigger volumes: Detecting when a player enters an invisible zone (like a checkpoint or a hazard area).
- Explosion radius: Determining which objects are within a spherical blast zone.
- Spawn safety checks: Verifying if a newly spawned item or character will overlap with existing environment geometry.
- Melee combat: Checking if a sword’s collision volume intersects with an enemy.
Key Differences
| Feature | Standard Raycast | Contact Test |
|---|---|---|
| Dimensionality | 1D (a thin line segment) | 3D (a volumetric shape) |
| Performance | Highly efficient and fast | More computationally expensive |
| Trigger Mechanism | Intersecting a line path | Overlapping of physical volumes |
| Result Data | Single hit point and surface normal | Penetration depth and contact manifolds |
Summary
Use a raycast when you need to detect line-of-sight, point-and-click interactions, or instantaneous linear travel. Use a contact test when you need to detect volumetric overlaps, volume-based triggers, or physical intersections of complex 3D shapes.