Phaser online editor

Write, Run & Share Phaser code online using OneCompiler's Phaser online editor for free. It's one of the robust, feature-rich online editors for Phaser. Getting started with the OneCompiler's Phaser online editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'Phaser' and start writing code to learn and test online without worrying about tedious process of installation.

About Phaser

Phaser is a framework for 2D games in the browser. You give it a config object describing the canvas and your scenes, and it runs the game loop, draws sprites, and handles input and physics. A scene moves through three stages: load assets, create objects, then update them every frame.

Syntax help

Setup

Load Phaser from a CDN, then create a game from a config. The config sets the size and the scene functions.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>
const config = {
  type: Phaser.AUTO,      // WebGL with a canvas fallback
  width: 640,
  height: 400,
  backgroundColor: '#1d1d2b',
  scene: { preload, create, update },
};

new Phaser.Game(config);

The scene lifecycle

preload loads assets, create sets up the scene once, and update runs every frame.

function preload() {
  this.load.image('logo', 'https://labs.phaser.io/assets/sprites/phaser3-logo.png');
}

function create() {
  this.logo = this.add.image(320, 200, 'logo');
}

function update() {
  this.logo.angle += 1;
}

Game objects

this.add creates text, images, and shapes. Shapes need no assets, so they're handy for quick demos.

function create() {
  this.add.text(20, 20, 'Score: 0', { fontSize: '24px', color: '#ffffff' });
  this.add.rectangle(320, 200, 64, 64, 0x5c6ac4);
  this.add.circle(120, 120, 30, 0xff3e00);
}

Tweens

this.tweens.add animates a property over time, with options for yoyo, repeat, and easing.

function create() {
  const box = this.add.rectangle(120, 200, 64, 64, 0x5c6ac4);
  this.tweens.add({
    targets: box,
    x: 520,
    angle: 360,
    duration: 1600,
    yoyo: true,
    repeat: -1,
    ease: 'Sine.easeInOut',
  });
}

Input

Read the keyboard with cursor keys, or respond to pointer events.

function create() {
  this.cursors = this.input.keyboard.createCursorKeys();
  this.input.on('pointerdown', (pointer) => {
    this.add.circle(pointer.x, pointer.y, 10, 0xffffff);
  });
}

function update() {
  if (this.cursors.right.isDown) this.logo.x += 4;
}

Physics

Enable the arcade physics engine in the config, then give objects velocity, gravity, and collisions.

const config = {
  type: Phaser.AUTO,
  width: 640,
  height: 400,
  physics: { default: 'arcade', arcade: { gravity: { y: 300 } } },
  scene: { preload, create },
};

function create() {
  const ball = this.physics.add.image(320, 50, 'logo');
  ball.setBounce(0.8).setCollideWorldBounds(true);
}