Deprecated This article was written based on Phaser 2.3, some of the information regarding the framework might not be applicable on later version of Phaser.

This is a part of series Phaser Camera.

  1. Write better camera for Phaser — Part 1
  2. Write better camera for Phaser — Part 2

I’ve been working with the HTML5 game engine Phaser. It is pretty decent and simple, very easy to learn and performs well on mobile devices.

However, I was making an top-down action game and wished to utilize some camera zooming and movement in order to deliver better effects and experiences. That’s when I realized Phaser.Camera does not have zoom functionality!

So I googled for some work around but the implementations are too messy and complicated for me. So I decided to make a DIY project.


My method is simple:

  1. Make a Phaser.Group, call it Camera.
     class Camera extends Phaser.Group {
     }
    
  2. Throw what I want to see in it.
  3. Scale it when I want to zoom.
     zoomTo(scale) {
         this.scale.setTo(scale)
     }
    

However, there is a problem: When zoomed out and panned, the camera panned outside of the group, like in the picture bellow.

By default, the bounds of game.camera is set to the size of game.world. While our group is originally identical to game.world, when the group is scaled, game.camera.bounds should also be scaled and repositioned accordingly.

    constructor() {
        ...
        this.bounds = Phaser.Rectangle.clone(game.world.bounds);
        ...
    }
    zoomTo(scale) {
        var bounds       = this.bounds;
        var cameraBounds = game.camera.bounds;
        cameraBounds.x      = bounds.width  * (1 - scale) / 2;
        cameraBounds.y      = bounds.height * (1 - scale) / 2;
        cameraBounds.width  = bounds.width  * scale;
        cameraBounds.height = bounds.height * scale;
        ...
    }

Finally, I added some tween to make the zoom smooth.

    zoomTo(scale, duration) {
        ...
        game.add.tween(cameraBounds).to({
            x      : bounds.width  * (1 - scale) / 2,
            y      : bounds.height * (1 - scale) / 2,
            width  : bounds.width  * scale,
            height : bounds.height * scale
        }, duration).start();
        return game.add.tween(this.scale).to({
            x: scale, y: scale
        }, duration).start();
    }

And then I had…

Read other posts in series Phaser Camera.

  1. Write better camera for Phaser — Part 1
  2. Write better camera for Phaser — Part 2
Loading comments

netcell

Software engineer with 4+ years of work experience in designing and developing cross-platform games and apps on web technology.