Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Input and Physics

Phaser Arcade Physics Basics: Gravity, Velocity and Bodies

Learn Arcade Physics in Phaser: enabling it, bodies, gravity, velocity, acceleration, drag, bounce, world bounds, body size and offset, static bodies and the debug view.

Phaser includes two physics engines. Arcade Physics is the fast, simple one: it works with axis-aligned rectangles and circles and handles gravity, speed, bouncing and collisions. Matter.js is the heavier, realistic one with rotation, polygons and joints. About nine out of ten 2D games (platformers, shooters, top-down games) only need Arcade, so that is where we start. You are not simulating the real world; you are giving your objects believable, controllable motion with very little code.

Turning physics on

Physics is configured in the game config (see The Game Configuration):

JavaScript
physics: {
  default: 'arcade',
  arcade: {
    gravity: { y: 600 },     // pixels per second squared, pulling down
    debug: true              // draw body outlines while developing
  }
}

Without this, this.physics does not exist. The gravity value is an acceleration: every second, a falling body's speed grows by 600 pixels per second. A y gravity makes a side-view game; leave it at 0 for a top-down game.

Bodies

A body is the invisible physics object attached to a game object. The game object is what you see; the body is what the engine moves and tests. There are three ways to get one:

JavaScript
this.physics.add.image(x, y, 'ball');       // image with a body
this.physics.add.sprite(x, y, 'hero');      // sprite with a body
this.physics.add.existing(someGameObject);  // add a body to an object you already made (a rectangle, text...)

Then use the body through obj.body or shortcut methods on the object itself (obj.setVelocity(...)).

There are two kinds of bodies:

  • Dynamic (default): moved by velocity, acceleration and gravity, and pushed by collisions.
  • Static (this.physics.add.staticImage, staticGroup, or add.existing(obj, true)): never moves. Perfect for floors and walls; the engine can skip them in movement calculations, which makes them cheaper.

The motion properties

Property / method What it controls
setVelocity(vx, vy), setVelocityX, setVelocityY speed in pixels per second
setAcceleration(ax, ay) a constant push that changes velocity over time
setGravityY(g) extra gravity for this body only (adds to the world gravity)
setDrag(dx, dy) slowing down when not accelerating (pixels per second squared)
setDamping(true) with drag 0.9 drag as a fraction kept each second (smoother)
setMaxVelocity(x, y) speed limit
setBounce(b) 0 = no bounce, 1 = full bounce, above 1 gains energy
setCollideWorldBounds(true) stay inside the world box
setFriction(x, y) surface friction (used on platforms, see later)
setMass(m), setImmovable(true) collision weight, or not pushable at all
setAngularVelocity(deg_per_s) spin the visual

The difference between velocity and acceleration matters: velocity is how fast you move, acceleration is how quickly velocity changes. A car pedal sets acceleration; the speedometer shows velocity. For a ship that speeds up and slides to a stop, use acceleration and drag. For a character that moves at once at a fixed speed, set velocity directly.

Gravity, bounce and world bounds

Four identical balls, four different bounce values: the red one stops dead on landing, the blue one bounces forever, because a bounce of 1 loses no energy. By default setCollideWorldBounds uses the whole game area as the world.

Acceleration and drag: a spaceship

A ship in space should speed up while the engine fires and coast to a stop afterward, which is exactly acceleration with drag. With keyboard input from the previous lesson, this takes five lines.

Acceleration, drag and max speed

velocityFromRotation(angle, speed, vector) fills vector with the x and y components for that speed in that direction: here the ship's acceleration. setDamping(true) with setDrag(0.4) means the ship keeps 40 percent of its speed each second when no thrust is applied, so it slows smoothly regardless of how fast it goes. Without damping, drag is a fixed amount in pixels per second squared and a slow ship stops abruptly while a fast one barely slows.

Body size, offset and shape

The body does not have to match the picture. A character's transparent edges should not collide.

JavaScript
sprite.body.setSize(20, 40);          // body width and height in pixels
sprite.body.setOffset(6, 8);          // shift the body inside the sprite's frame
sprite.body.setCircle(12);            // round body with radius 12 (use setCircle(r, offsetX, offsetY))

Remember the body sits inside the unscaled frame, and the sprite's scale scales the body too. Turn on debug: true and look at the green rectangle: when it does not hug the part that should collide, adjust the size and offset until it does. Use slightly smaller bodies than the art: the game feels fair when the player is almost touched but not hit.

Arcade bodies are axis-aligned: they never rotate. If your ship rotates 45 degrees, the body stays an upright box (or circle). A circle body is a good fit for rotating objects.

Useful body information

Property Meaning
body.velocity.x / .y, body.speed current motion
body.blocked.down, .up, .left, .right stopped by the world bounds or a collider
body.touching.down ... touching another body (after a collision)
body.onFloor() true when blocked below: perfect for "can jump"
body.position, body.center, body.bottom box coordinates
body.enable false to switch the body off

World bounds

By default the world is as big as the game. Change it with this.physics.world.setBounds(0, 0, 3200, 600) for a level that is wider than the screen (with a scrolling camera). setBoundsCollision(left, right, up, down) chooses which sides are solid. The event worldbounds fires when a body with body.onWorldBounds = true hits an edge: useful to destroy bullets that leave the arena.

Moving without gravity: the helpers

Arcade also offers shortcuts for common movement:

  • this.physics.moveToObject(obj, target, speed) sets velocity toward another object (homing enemy).
  • this.physics.moveTo(obj, x, y, speed) toward a point.
  • this.physics.accelerateToObject(obj, target, accel) accelerates toward a target.
  • this.physics.velocityFromAngle(deg, speed, out) and velocityFromRotation (radians) convert an angle to a velocity vector.
  • this.physics.closest(obj) and furthest(obj) find the nearest or farthest body.

Pausing and slowing physics

this.physics.pause() and resume() stop and restart the simulation. this.physics.world.timeScale = 2 makes it run slower (counterintuitively, larger means slower: it scales the step duration). this.physics.world.fps sets the physics step rate (60 by default); physics always uses a fixed step, so it behaves the same on fast and slow machines. That is why you do not multiply velocities by delta time.

Common mistakes

  • Using x += 5 on a physics object. Let physics move it with velocity, or you fight the engine. (Direct moves are fine for kinematic objects you control entirely, but then collisions will not push them correctly.)
  • Forgetting physics in the config. this.physics is undefined.
  • Gravity pulling things you did not want to fall (floors, clouds). Use static bodies, or body.setAllowGravity(false).
  • A body bigger or smaller than the picture. Turn on debug: true.
  • Setting velocity every frame when you meant acceleration. The ship cannot coast.
  • Large-speed tunneling. A very fast small body can skip through a thin wall between two steps; use thicker walls or lower speeds.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a gravity of { y: 600 } mean in Arcade Physics?

    Gravity is an acceleration in pixels per second squared, so velocity grows steadily while falling.
  2. 2. Which kind of body should a floor use?

    Static bodies are for fixed scenery like floors and walls.
  3. 3. What is the difference between velocity and acceleration?

    Acceleration changes velocity over time, which makes speeding up and slowing down smooth.
  4. 4. Why should you NOT multiply physics velocities by delta time?

    Velocity is in pixels per second and the physics world steps at a fixed rate, so it is already frame-rate independent.
  5. 5. How can you see body outlines while building your game?

    Debug mode draws the green body boxes and velocity lines, which makes size and offset problems obvious.

Summary

  • Enable Arcade Physics in the config; give objects bodies with physics.add.image/sprite/existing; use static bodies for fixed scenery.
  • Control motion with velocity (direct), acceleration (gradual), drag, damping, bounce and max velocity.
  • Size and offset bodies to match the part that should collide; arcade bodies are axis-aligned boxes or circles.
  • Use blocked/touching/onFloor() to read contacts, world bounds to limit the arena and debug: true to see it all.
  • Physics has its own fixed time step: set velocities in pixels per second without delta time.

Next: Collisions, Overlaps and Groups