What is a Chain Shape in Planck.js?
This article provides an overview of the chain shape in Planck.js, a 2D physics engine for JavaScript. It covers what a chain shape is, its key characteristics, and the specific scenarios where you should use it instead of other shape types like polygons or edges.
Understanding the Chain Shape
In Planck.js (which is a JavaScript port of the Box2D physics engine), a chain shape is a collection of line segments linked together to form an open or closed path. It provides an efficient way to connect multiple vertices into a single shape, allowing you to create complex, winding static boundaries without the overhead of creating dozens of individual edge shapes.
Key Characteristics
- Ghost Vertices: Chain shapes support “ghost vertices” at the beginning and end of the chain. These are hidden vertices that help the physics engine smoothly calculate collisions when a dynamic body slides across the joints between segments, preventing the object from getting stuck on internal corners.
- No Volume: Because it consists entirely of line segments, a chain shape has no area or volume. Consequently, it does not have a mass or moment of inertia.
- Two-Sided Collision: Collisions can occur on both sides of a chain shape segment, unlike polygons which only collide on their exterior faces.
When to Use a Chain Shape
Chain shapes are highly specialized and should be used under specific circumstances within your physics simulation.
1. Creating Complex Static Terrains
If your game or simulation features a continuous, uneven ground—such as a rocky hillside, a cavern floor, or a racing track—a chain shape is the ideal choice. It allows you to define the entire landscape using an array of coordinates, ensuring seamless physics interactions as objects move across it.
2. Eliminating Internal Collision Glitches
When you line up multiple individual box or edge shapes side-by-side to form a floor, moving objects can occasionally “snag” on the microscopic gaps or seams between them due to floating-point math inaccuracies. A chain shape eliminates this issue entirely by treating the connected segments as a single cohesive boundary with internal smooth-sliding logic.
3. Simulating Hollow Containers
Because chain shapes can be closed (connecting the last vertex back to the first), they are perfect for creating the inside walls of a container, a cage, or a hollow room where dynamic objects need to bounce around inside the perimeter.
Important Limitations
While powerful, chain shapes come with strict rules:
- Static Bodies Only: Chain shapes should only be
attached to static physics bodies (
Body.STATIC). They are not designed to be used on dynamic or kinematic bodies that move around and react to forces. - No Self-Intersection: The segments of a chain shape should never cross over one another, as self-intersection can confuse the collision detection algorithms and cause unpredictable physics behavior.