Game development with JS and Phaser

@ladybenko

Why making games in JS?

Because we can :)

Phaser

A game in a weekend

Slides & examples

belen-albeza.github.io/mediterranea-js-2015

Press start button

What do we need to make a game?

The game loop

Init Phaser

var loop = {
  preload: function () {},
  create: function () {},
  update: function () {},
  render: function () {}
};

window.onload = function ()  {
  new Phaser.Game(640, 480, Phaser.WEBGL, 'wrapper', loop);
};

Images and sprites

Draw images

function preload () {
  this.game.load.image('background',
    '../assets/images/trees.png');
}

function create () {
  this.game.add.image(0, 0, 'background');
}

Sprites

Sprites

Use Phaser.Sprite

var ship = new Phaser.Sprite(this.game, 10, 20, 'hero');

or use game's factory

var ship = this.game.add.sprite(10, 20, 'hero');
ship.anchor.setTo(0.5, 0.5);
ship.angle = 45;
ship.alpha = 0.5;

Animations

function preload() {
  this.game.load.spritesheet('hero',
    'character.png', 122, 256);
};

function create() {
  var hero = this.game.add.sprite(320, 240, 'hero');
  hero.animations.add('walk');
  hero.animations.play('walk', 5, true);
}

Move sprites (old-school)

var SHIP_SPEED = 100; // pixels / second

function update() {
  // time in seconds
  var delta = this.game.time.elapsed / 1000.0;
  
  // position = speed * time
  ship.x += SHIP_SPEED * delta;
}

The game tree

The game tree

Create & destroy sprites

Add and remove them from the tree

PROBLEM: it's expensive!

Recycle sprites

Input, audio & text

Input

function create() {
  // capture spacebar key
  spacebar = game.input.keyboard.addKey(
    Phaser.Keyboard.SPACEBAR);
  game.input.keyboard.addKeyCapture(
    [Phaser.Keyboard.SPACEBAR]);
    
  // register event callback
  spacebar.onDown.add(shoot);
}
// check key flag
function update() {
  if (spacebar.isDown) {
    shoot();
  }
}

Audio

// within preload
game.load.audio('shoot', 'laser.wav');

// within create
sfxShoot = game.add.audio('shoot');

// anywhere
sfxShoot.play();

Text

title = game.add.text(0, 0, 'Score', {
  font: '20px monospace',
  fill: '#f00'
});

title.setText('Score: ' + score);

Physics and collisions

Collisions with b-boxes

Physics engines

Physics engines

The rest

The golden rule about game dev

If you can fake it, then fake it.

You should also look into

Examples for this talk

Snippets and a game!

Links

Thanks!

Questions?