arcade-physics 0.2.0 preview

Arcade Physics, without Phaser

arcade-physics is Phaser's Arcade Physics on its own. Simulate 2D bodies, bounces and tile collisions in vanilla JavaScript, in a PixiJS scene, or on a Node.js server.

This page describes 0.2.0, which adds tilemaps and Phaser 4's Arcade Physics. npm still lists 0.1.0 until the release.

Live demo Loading the library

Every position in this demo comes from arcade-physics. The canvas only draws them. Click the canvas to drop a ball there.

01 The loop

The library simulates. Your code draws.

arcade-physics tracks positions, velocities and collisions. It never touches the screen. Each frame you advance the world, read the bodies, and draw them with Canvas, PixiJS, or not at all.

  1. Once Create the world

    Load the world, then add bodies and colliders. Setup runs one time.

  2. Each frame world.update()

    Gravity and velocity move every body. Colliders push overlapping bodies apart.

  3. Each frame world.postUpdate()

    Finish the step. Call it after every update.

  4. Each frame Draw

    Read body.x, body.y or body.center, then draw with any renderer.

loop.js
// Once, during setup
const physics = await LoadArcadePhysics({ width: 640, height: 360, gravity: { x: 0, y: 600 } })
const ball = physics.add.body(120, 40)
ball.setCircle(16)
ball.setBounce(0.7)
ball.setCollideWorldBounds(true)

// Every frame
let last = performance.now()
let time = 0

function frame(now) {
  // Clamp long gaps, for example after the tab was hidden.
  const delta = Math.min(now - last, 100)
  last = now

  physics.world.update(time, delta)
  physics.world.postUpdate()
  time += delta

  draw(ball.center.x, ball.center.y, ball.radius)
  requestAnimationFrame(frame)
}
requestAnimationFrame(frame)

02 Vanilla JavaScript

A canvas, a module and a loop

No framework is needed. The live demo at the top runs this same pattern, with more bodies. Give the library a width, height and gravity, then draw each body where its x, y and center say it is.

  • Fixed steps. The world steps at 60 per second by default. Each update() call runs at most one step, so call it once per frame.
  • One-way data. The library never reads your canvas. You copy positions out.
  • Debug view. body.drawDebug() with DebugGraphics outlines every body on a 2D context.
index.html + main.js
// index.html has one canvas and one module script:
// <canvas id="stage" width="640" height="360"></canvas>
// <script type="module" src="./main.js"></script>

import { LoadArcadePhysics } from 'arcade-physics'

const canvas = document.getElementById('stage')
const ctx = canvas.getContext('2d')

const physics = await LoadArcadePhysics({ width: 640, height: 360, gravity: { x: 0, y: 600 } })

const floor = physics.add.staticBody(0, 330, 640, 30)
const ball = physics.add.body(120, 40)
ball.setCircle(16)
ball.setBounce(0.7)
ball.setCollideWorldBounds(true)
physics.add.collider(ball, floor)

let last = performance.now()
let time = 0

function frame(now) {
  const delta = Math.min(now - last, 100)
  last = now
  physics.world.update(time, delta)
  physics.world.postUpdate()
  time += delta

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#334155'
  ctx.fillRect(floor.x, floor.y, floor.width, floor.height)
  ctx.fillStyle = '#a3e635'
  ctx.beginPath()
  ctx.arc(ball.center.x, ball.center.y, ball.radius, 0, Math.PI * 2)
  ctx.fill()

  requestAnimationFrame(frame)
}
requestAnimationFrame(frame)

No bundler? After 0.2.0 is published, you can import the package from a CDN with import { LoadArcadePhysics } from 'https://esm.sh/arcade-physics@0.2.0'.

03 PixiJS

Physics moves the bodies. Pixi draws the sprites.

Pixi owns the display list. arcade-physics owns the bodies. Each frame, copy the body's center into the sprite. The physics world never reads sprite state, so the same simulation runs with or without a renderer.

  1. arcade-physics Body

    Holds position, velocity and shape. Updated by world.update().

  2. Your code sprite.position.set()

    Copies body.center into the sprite once per frame.

  3. PixiJS Sprite

    Draws the texture where the body is. Pixi never changes the body.

  • Pixi 8 API. Use app.init() and app.ticker, as the Pixi.js page does.
  • Clamp the delta. The ticker reports the time since the last frame. Clamp it, so a hidden tab does not fast-forward the physics.
  • Anchor at the center. Sprites that use anchor 0.5 line up with body.center.
pixi-physics.js
import { Application, Assets, Sprite } from 'pixi.js'
import { LoadArcadePhysics } from 'arcade-physics'

const app = new Application()
await app.init({ width: 640, height: 360, background: '#07080d' })
document.body.appendChild(app.canvas)

const physics = await LoadArcadePhysics({ width: 640, height: 360, gravity: { x: 0, y: 600 } })
const floor = physics.add.staticBody(0, 330, 640, 30)
const ball = physics.add.body(120, 40)
ball.setCircle(16)
ball.setBounce(0.7)
ball.setCollideWorldBounds(true)
physics.add.collider(ball, floor)

// ball.png is a 32 by 32 image
const sprite = new Sprite(await Assets.load('ball.png'))
sprite.anchor.set(0.5)
app.stage.addChild(sprite)

let time = 0
app.ticker.add(({ deltaMS }) => {
  const delta = Math.min(deltaMS, 100)
  time += delta
  physics.world.update(time, delta)
  physics.world.postUpdate()
  sprite.position.set(ball.center.x, ball.center.y)
})

04 Node.js

The same world, with no browser

The package's tests run in plain Node.js. A server can step the same physics the browser shows, with no canvas, no timers and no DOM. Typical uses are a server that owns the game state, bots, replays and simulation tests in CI.

server.mjs
import { LoadArcadePhysics } from 'arcade-physics'

const physics = await LoadArcadePhysics({ width: 800, height: 450, gravity: { x: 0, y: 300 } })

const box = physics.add.body(20, 20, 64, 64)
box.setCollideWorldBounds(true)

const platform = physics.add.staticBody(60, 350, 160, 32)
physics.add.collider(box, platform)

// Advance the world in 1/60 s steps. No timers, no DOM.
const step = 1000 / 60
for (let frame = 0; frame <= 120; frame++) {
  physics.world.update(frame * step, step)
  physics.world.postUpdate()
  if (frame % 20 === 0) console.log(`frame ${frame}: x=${box.x.toFixed(1)} y=${box.y.toFixed(1)}`)
}

console.log('final', { x: box.x, y: box.y, onFloor: box.onFloor() })

$node server.mjs

frame 0: x=20.0 y=20.1

frame 20: x=20.0 y=39.3

frame 40: x=20.0 y=91.8

frame 60: x=20.0 y=177.6

frame 80: x=20.0 y=286.0

frame 100: x=20.0 y=286.0

frame 120: x=20.0 y=286.0

final { x: 20, y: 286, onFloor: true }

  • Deterministic. Two runs print the same numbers. The package's test suite checks exact positions after each step.
  • Node module. The example is an ES module, so use a .mjs file or set "type": "module".

05 Tilemaps new in 0.2.0

Collide bodies with a grid of tiles

Describe the level as rows of numbers. Zero is empty and any other number is a solid tile. Build a tile layer, turn the grid into tiles, then call collideBodyVsTiles() for each body after every step.

  • Plain objects. Each tile exposes x, y and index. Use the index to tell tile types apart.
  • Per-tile callbacks. A tile's collisionCallback, set with createTile(), returns false to ignore that tile for one body. The collideCallback option runs after each hit.
  • Rectangles only. Tile collisions check the body's rectangle, so give tile-colliding bodies a box shape.
  • Grids only. Tiles come from arrays. This API does not load Tiled map files.
Live tilemap Waiting for the demo to load
Grey blocks are solid tiles.
tilemap.js
import {
  LoadArcadePhysics,
  createTileLayer,
  createTilesFromGrid,
  collideBodyVsTiles
} from 'arcade-physics'

// 0 is empty. Any other number is a solid tile.
const grid = [
  [0, 0, 0, 0, 0, 0],
  [0, 0, 1, 1, 0, 0],
  [1, 1, 1, 1, 1, 1]
]

const physics = await LoadArcadePhysics({ width: 192, height: 96, gravity: { x: 0, y: 600 } })
const layer = createTileLayer({ tileWidth: 32, tileHeight: 32 })
const tiles = createTilesFromGrid(layer, grid)

const box = physics.add.body(40, 20, 12, 12)
box.setBounce(0.5)

let time = 0
// Call frame(delta) from your loop, with the milliseconds since the last frame.
function frame(delta) {
  physics.world.update(time, delta)
  collideBodyVsTiles(box, tiles) // push the box out of solid tiles
  physics.world.postUpdate()
  time += delta
}

06 What changed

Moving from 0.1.0 to 0.2.0

0.1.0 is what npm installs today. 0.2.0 switches to Phaser 4's Arcade Physics and adds tilemaps.

Topic 0.1.0 (npm today) 0.2.0 (next release)
Create a world new ArcadePhysics(config) await LoadArcadePhysics(config)
Config width, height, gravity Same keys: width, height, gravity
Tilemaps Files are present, but not usable yet createTileLayer, createTilesFromGrid, collideBodyVsTiles, overlapBodyVsTiles
Physics source Phaser's Arcade Physics, converted to TypeScript Phaser 4's Arcade Physics source, built as a standalone bundle
Debug drawing body.drawDebug(ctx) takes a 2D context body.drawDebug(new DebugGraphics(ctx))

Migrating a 0.1.0 project: replace new ArcadePhysics(config) with await LoadArcadePhysics(config). The body and world calls stay the same.

07 Install

Add it with npm

Install the package in any Node.js or bundler project. Pin the version once 0.2.0 is on npm.

$npm install arcade-physics

$npm install arcade-physics@0.2.0

Do I need Phaser?
No. The package contains the Arcade Physics code, not a Phaser game, scene or renderer.
Does it draw anything?
No. You draw. DebugGraphics is a helper that outlines bodies on a 2D context for debugging.
Can I load Tiled maps?
Not with this API. Build tiles from a grid array with createTilesFromGrid.
Why does my body fall through a tile?
Tile collisions check the body's rectangle, and ignore a circle shape. Give bodies that collide with tiles a box shape.