FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

Game Mechanic: Extending the Game Size

 

The game mechanic or rather element of changing the space the player can move around in is essential to many platform games.

Let's look at how we can extend our world so that when our player starts to move towards the edges, the world scrolls to reveal more space.

 

Check the Code: what we need to know and do

Our approach relies on the following exiting knowledge;

To make this work we need to do three main things.
  • increase the size of our world size without increasing the screen size
  • set up a "camera" to follow our player as they move
  • set the background image so that it loops
The code for a minimal example of the Extending the Game Size is shown here -  https://game-mechanic-extend-game-world.glitch.me/
 

Going over the code:

First note that we should add a new variable var background at the start of our code.

Then have a look at some key code in the create function;

    background  = game.add.tileSprite(0, 0, 480, 360, 'background');
    game.world.setBounds(0, 0, 900, 360);

Here we set background to be a tileSprite 1 a special type of sprite that is useful here when we need scrolling backgrounds .

We also set the bounds of the world to be wider than the game size created when we created the game object. Here we have a width of 900, you can change this to experiment with bigger or smaller worlds. 

To make the focus of the game follow the player, so that for the most part the player stays in the centre of the screen, we set a camera to follow the player and for the background to also move with along with the camera

    game.camera.follow(player);
    background.fixedToCamera = true

Finally in update, this next line of code creates the scrolling and looping effect. You can comment it out to see the difference. 

    background.tilePosition.set(-game.camera.x,-game.camera.y); 

There are more details on using tileSprites including a nifty tip right at the end to use a parallax effect in a chapter here 2.

That's it. We hope you enjoy adding this game dynamic to your game to extend your game size.

 

  1. https://photonstorm.github.io/phaser-ce/Phaser.TileSprite.html ^
  2. https://docs.idew.org/video-game/project-references/phaser-coding/tilesprite-scrolling ^

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.