Create a Capsule Shape Using Chamfer in Matter.js
Matter.js does not feature a dedicated capsule primitive, but you can create an accurate capsule collider by applying a chamfer to a standard rectangle body. This article explains how to configure a rectangle's dimensions and chamfer radius to produce a capsule, provides a ready-to-use code implementation, and covers key settings such as vertex quality.
How the Chamfer Method Works
A capsule (also known as a stadium shape) consists of a rectangle
capped by two semicircular ends. In Matter.js, the chamfer
property bevels the corners of a polygon by generating additional
vertices along a curve.
To form a true capsule:
- Choose the capsule orientation (vertical or horizontal).
- Set the chamfer radius to exactly half of the shorter dimension.
- For a vertical capsule of width \(W\) and height \(H\) (where \(H > W\)), the chamfer radius must be \(W / 2\).
- For a horizontal capsule where \(W > H\), the chamfer radius must be \(H / 2\).
Applying this radius rounds the adjacent corners together, forming seamless semicircular caps on both ends of the body.
Code Example
To generate a vertical capsule, define the rectangle and pass the
chamfer configuration in the body options:
const Matter = require('matter-js');
const { Bodies } = Matter;
const x = 400;
const y = 300;
const width = 60;
const height = 140;
// Radius must equal half the width for a vertical capsule
const capsuleRadius = width / 2;
const capsule = Bodies.rectangle(x, y, width, height, {
chamfer: {
radius: capsuleRadius,
quality: 8 // Controls the smoothness of the curve
},
render: {
fillStyle: '#2ecc71'
}
});Configuring Chamfer Settings
The chamfer option accepts two primary properties:
radius: A number or an array of numbers specifying the corner radius. For a uniform capsule, pass a single number equal to half the smaller dimension.quality: Controls how many vertices are generated to approximate the rounded corners. The default value is-1(automatic based on radius). Setting a specific integer, such as8or10, ensures smooth curves without generating an excessive number of vertices.
Chamfer vs. Compound Bodies
Using a chamfered rectangle is generally preferred over building a compound body made of two circles and a rectangle:
- Performance: A chamfered rectangle remains a single convex polygon. Matter.js processes single convex bodies faster than compound bodies consisting of multiple sub-parts.
- Simplicity: Chamfered bodies have a single center of mass and unified inertia automatically calculated by the engine.
- Collision Artifacts: Compound shapes can occasionally cause internal edge catching or collision jitter at the seam between the circles and the central rectangle. A chamfered polygon eliminates this issue entirely.