It’s not obvious what a plane is in a 2D physics engine.

Versions used below

{
  "p2": "0.6.1"
}

Circles, rectangles and lines make sense in 2D but a plane feels more relevant in 3D worlds. Sure, a 2D world exists on one plane but that’s not what a plane is in p2.

Thinking about planes in p2

A plane is a shape that extends infinitely in three directions (e.g. left, down, right). There is a flat edge on the other, non-infinite side.

Planes as edges of the world

Planes have one flat edge and nothing can get around or behind them. This makes planes a good candidate for edges of the game world.

Floor

The default plane orientation acts as a floor. It stretches down, left and right forever.

var floor = new p2.Body();

floor.addShape(new p2.Plane());

Ceiling

Flipping it by 180 degrees makes a ceiling.

var ceiling = new p2.Body({
  // radians
  angle: Math.PI
});

ceiling.addShape(new p2.Plane());

Right wall

Increasing a body’s angle rotates it in the counterclockwise direction.

Right wall is rotated 90 degrees from the floor.

var right = new p2.Body({
  angle: Math.PI / 2
});

right.addShape(new p2.Plane());

Left wall

Left wall is rotated 270 degrees from the floor.

var left = new p2.Body({
  angle: (3 * Math.PI) / 2
});

left.addShape(new p2.Plane());

Angled

You can use any angle to get slopes.

var ramp = new p2.Body({
  // ramp from bottom/left to top/right
  angle: Math.PI / 4
});

ramp.addShape(new p2.Plane());

Prefer planes over lines and rectangles

Lines and rectangles could be used for edges of the world but planes have a few advantages.

  1. You don’t have to worry about planes being wide or tall enough. Nothing can get around or behind a plane.

  2. Planes collide with more shapes than Lines and Rectangles do.

Positioning planes

Position of a plane is a little weird to think about. I’ve found that a plane’s edge will intersect its position coordinate.

p2 is “y up”, y values increase as you go up. To put a floor 10 units above the origin I would use

var floor = new p2.Body({
  // the x value is irrelevant here, the plane spans the entire x axis
  position: [0, 10]
});

floor.addShape(new p2.Plane());

To put a left wall 100 units to the right of the origin

var leftWall = new p2.Body({
  angle: (3 * Math.PI) / 2,
  // now the y value is irrelevant
  position: [100, 0]
});

leftWall.addShape(new p2.Plane());