Max Vertex Limit for Polygons in Planck.js
This article provides a direct overview of the vertex limitations when creating polygon shapes in planck.js, a 2D JavaScript physics engine based on Box2D. We will explore the default hardcoded limits, the reasoning behind these constraints, and how you can work around them if your project requires more complex geometry.
The Default Vertex Limit
In planck.js, the maximum number of vertices allowed for a single
PolygonShape is 8.
If you attempt to pass an array containing more than 8 vertices into the polygon shape definition, the engine will typically throw an error or fail to simulate the shape correctly.
Why is There a Limit?
This restriction is inherited directly from Box2D’s design philosophy and is deeply tied to performance and stability:
- Performance Optimization: Physics engines must perform collision detection calculations at 60 frames per second (or higher). Limiting the number of vertices keeps the mathematical calculations per shape predictable and fast.
- Memory Management: Fixed-size arrays are highly efficient. Allocating a small, constant amount of memory for each shape prevents dynamic allocation overhead during the simulation.
- Convex Requirements: Planck.js requires all polygon shapes to be convex (meaning no internal angles are greater than 180 degrees). Keeping vertex counts low makes it easier to validate and maintain convex hulls.
How to Bypass the Limitation
If your game or application requires a shape with more than 8 vertices, or a complex concave shape, you can use the following standard workarounds:
1. Convex Decomposition
You can break a complex or high-vertex shape down into multiple
smaller convex polygons, each having 8 or fewer vertices. You then
attach all of these individual polygon shapes to a single rigid
Body. The body will move and behave as one unified
object.
2. Using Chain Shapes
If you only need the boundary or outline of a complex shape
(for example, terrain or map boundaries) rather than a solid, filled
object, you should use a ChainShape. Chain shapes allow for
a virtually unlimited number of vertices connected in a series, making
them perfect for static environment geometry.