How to Create a Circle in Planck.js?
Planck.js is a 2D physics engine for JavaScript cross-platform development, rewritten from Box2D. Creating a circle shape involves defining a world, creating a body within that world, and attaching a circle shape fixture to it. This article will guide you through the precise steps and code required to set up a rigid body with a circular geometry in your Planck.js simulation.
Setting Up the Circle Shape
To create a circular object in Planck.js, you need to follow the
standard Box2D workflow: define the body, create the body in the world,
define the shape, and attach the shape as a fixture. The
pl.Circle function is specifically used to define the
geometry by specifying its radius.
Step-by-Step Code Implementation
Here is the standard way to create a dynamic circle body in your physics world:
// 1. Initialize the Planck.js world
const world = pl.World({
gravity: pl.Vec2(0, -10)
});
// 2. Create the body definition and the body itself
const body = world.createBody({
type: 'dynamic',
position: pl.Vec2(0, 5)
});
// 3. Define the circle shape by passing the radius
// This creates a circle with a radius of 2.0 meters
const circleShape = pl.Circle(2.0);
// 4. Attach the shape to the body using a fixture
body.createFixture({
shape: circleShape,
density: 1.0,
friction: 0.3
});Key Parameters Explained
pl.Circle(radius): The core function that defines the geometry. It takes a single number representing the radius in physics world meters.density: Determines the mass of the object based on its area. A higher density makes the circle heavier.position: Apl.Vec2object indicating where the center of the circle will initially spawn in the 2D coordinate system.