Get Polygon Vertex Coordinates in Matter.js
This article explains how to retrieve the exact coordinates of all vertices for a polygon body in Matter.js. Whether you need vertex data for custom rendering, custom collision logic, or debugging geometry, Matter.js exposes these points directly through the body's internal properties. Below, you will find the direct method to read these points, along with code examples for both simple and compound bodies.
Accessing Vertices on a Simple Body
In Matter.js, any rigid body created with polygon geometry stores its
current world-space vertices in the body.vertices array.
These coordinates update automatically as the body moves, rotates, or
scales during the physics simulation.
Each element in the body.vertices array is a vector
object containing x and y properties.
// Example: Creating a regular polygon
const polygon = Matter.Bodies.polygon(400, 300, 5, 50);
Matter.Composite.add(engine.world, polygon);
// Reading the vertex coordinates
const vertices = polygon.vertices;
vertices.forEach((vertex, index) => {
console.log(`Vertex ${index}: X = ${vertex.x}, Y = ${vertex.y}`);
});To extract the coordinates into a plain array of coordinate objects:
const points = polygon.vertices.map(v => ({ x: v.x, y: v.y }));
console.log(points);Handling Compound Bodies
If your polygon is part of a compound body (a body formed by
combining multiple shapes), accessing compoundBody.vertices
might only return the convex hull of the entire assembly or the vertices
of the parent container.
To read the vertices of every individual polygon within a compound
body, iterate over body.parts:
// Iterate through each part of a compound body
// Index 0 is the parent body itself, so start at index 1 for individual sub-shapes
for (let i = 1; i < compoundBody.parts.length; i++) {
const part = compoundBody.parts[i];
console.log(`Part ${i} vertices:`);
part.vertices.forEach((vertex, vIndex) => {
console.log(` Vertex ${vIndex}: (${vertex.x}, ${vertex.y})`);
});
}Local Coordinates vs. World Coordinates
The coordinates provided by body.vertices are in
absolute world space. If you require coordinates relative to the body’s
center point (body.position), subtract the center
coordinates from each vertex:
const localVertices = polygon.vertices.map(vertex => ({
x: vertex.x - polygon.position.x,
y: vertex.y - polygon.position.y
}));