How to Set Gravity in Planck.js?

This article provides a quick overview and practical guide on how to define the gravity vector in a planck.js world. You will learn the syntax for initializing gravity during world creation, how to alter it dynamically during runtime, and how to manipulate gravity for individual physics bodies.

— (Wait, user said “Don’t create any horizontal rules in the article.” Let me remove that. Ah, good catch. Re-evaluating text without horizontal rules).

How to Set Gravity in Planck.js?

This article provides a quick overview and practical guide on how to define the gravity vector in a planck.js world. You will learn the syntax for initializing gravity during world creation, how to alter it dynamically during runtime, and how to manipulate gravity for individual physics bodies.

Initializing Gravity During World Creation

In planck.js—a 2D JavaScript physics engine based on Box2D—gravity is defined as a 2D vector using the Vec2 object. This vector dictates the direction and strength of the gravitational force acting on dynamic bodies within your simulation.

To set the gravity when creating a new world, you pass a Vec2 instance into the World constructor.

const { World, Vec2 } = require('planck-js');

// Define gravity pointing downwards (e.g., 9.8 m/s²)
const gravity = Vec2(0, -9.8);

// Create the world with the defined gravity
const world = World(gravity);

In this setup, the first parameter of Vec2 represents the horizontal axis (X), and the second parameter represents the vertical axis (Y). A negative Y value pulls objects downward, simulating standard real-world gravity.

Modifying Gravity at Runtime

If your game or simulation requires environmental changes—such as a gravity flip, space environments, or wind forces—you can alter the world’s gravity vector dynamically after the world has been initialized.

This is achieved using the setGravity() method on your world instance:

// Change gravity to pull objects upward
world.setGravity(Vec2(0, 9.8));

// Change gravity to pull objects to the right (sideways gravity)
world.setGravity(Vec2(5.0, 0));

// Turn off global gravity entirely
world.setGravity(Vec2(0, 0));

Any changes made via setGravity() will immediately apply to all dynamic bodies in the next physics step simulation (world.step()).

Adjusting Gravity for Specific Bodies

Sometimes you may want the global gravity to remain constant while making a specific object float, fall faster, or defy physics. Planck.js allows you to adjust how gravity affects individual bodies using the setGravityScale() method.

// Create a dynamic body
const body = world.createBody({
  type: 'dynamic',
  position: Vec2(0, 10)
});

// Make this specific body immune to the world's gravity vector
body.setGravityScale(0);