How do you initialize a new physics world in planck.js?

Initializing a new physics world in planck.js is the foundational step for managing physical bodies, joints, and real-time simulation in your 2D JavaScript games. By instantiating a central world container and defining a custom gravity vector, you establish the environment where all subsequent rigid-body interactions take place. This guide walks you through the required code, configuration parameters, and the process of updating the environment over time.

Step 1: Import the Library

Before creating a simulation environment, ensure the library is included in your project. You can import the global constructor or destructured classes depending on your module setup.

// Using ES6 modules
import { World, Vec2 } from 'planck';

// Using CommonJS
const planck = require('planck');
const World = planck.World;

Step 2: Define Configuration Options

The World constructor accepts a configuration object. While several options exist, the two most critical settings to provide are gravity and rigid-body sleeping behavior.

Step 3: Instantiate the Physics World

To construct the world, invoke the World constructor with your configuration settings.

// Configure and initialize the physics world
const world = new World({
  gravity: new Vec2(0, -10), // Heavy downward gravity on the Y-axis
  allowSleep: true           // Performance optimization for idle bodies
});

Step 4: Advance the Simulation

A physics world requires explicit continuous updates to calculate movement and collisions over time. This is achieved by calling the .step() method inside your game’s main loop or a tracking interval.

The step method requires a fixed time interval, usually matching your frame rate.

const timeStep = 1 / 60; // 60 frames per second

function gameLoop() {
  // Advance the physics world by the specified time increment
  world.step(timeStep);
  
  // Request next frame
  requestAnimationFrame(gameLoop);
}

// Start the simulation loop
requestAnimationFrame(gameLoop);