Home Java Creating your first gameon Phaser.Part 2- Loading Resources

Creating your first gameon Phaser.Part 2- Loading Resources

by admin

Creating your first gameon Phaser.Part 2- Loading Resources

Table of contents

0 Preparation for work
1 Introduction
2 .Resource Loading [ You are here ]
3 Creating a game world
4 ( wip ) Groups
5 ( wip ) World of Physics
6 ( wip ) Management
7 ( wip ) Adding targets
8 ( wip ) The finishing touches

Let’s continue the series of lessons on the use of Phaser in conjunction with TypeScript In this lesson, we will look at loading resources in Phaser , as well as a little "brush" code from the previous part.

As in past articles, don’t skip comments in the code.

The full code written in this article can be found at Github repositories with the tag part-2

Let’s get started!


First of all, let’s organize the previouslywritten code more correctly :

Firstly , create a directory src/states and put the file src/states/state.ts :

'use strict';/** Imports */import Appfrom ';Abstract class Stateextends Phaser.State.{// Let's rewrite the `game` property of our stats.This is done // so that if we add a field to the `App`, the TypeScript// pick it up and not complain about it if we call it with the// `this.game`.game:App;}export default State;

We created an abstract class State and inherited it from the Phaser.State This seemingly strange manipulation is necessary in order to TypeScript handled the property this.game in the methods of our stats. By default, the property game has the type – Phaser.Game , and accordingly TypeScript would have learned nothing about the fields we added to App (In this series of articles, we will not be adding custom fields to App but it wouldn’t hurt to have such an abstract class beforehand).

You’re probably wondering : "Which property might we even want to add to the App ?". Since each state has a property-reference to Appthis.game we can, for example, add the App a global dependency for all stats, or a reference to a storage object, a WebSocket connection, etc.

Second , let’s move our MainState in src/states/main.state.ts and remove unnecessary, at present, methods from it ( preload and update ):

'use strict';/** Imports */import State from './state';// Main state of the gameexport default class MainStateextends State {create():void{ }}

And in src/index.ts let’s add to 10 The import line of this stack :

// ...import MainState from './states/main.state';// ...

Third , create BootState and PreloaderState in src/states/boot.state.ts and src/states/preloader.state.ts , respectively :

'use strict';/** Imports */import State from './state';// This state is needed to load critical resources before `preloader`;//for displaying information in the console;//for other initial manipulations;export default class BootStateextends State {create(): void{// `this.game` is a reference to the instance of our `App` we've added the// this state.This.game.state.start('preloader'); // Switch to `preloader` state}}


'use strict';/** Imports */import State from './state';// In this state we will load all the core resources for our game:// * Logos, splashscreens// Menu sprites// * Sounds of pressing the screen / buttons// * And so on.export default class PreloaderStateextends State {preload(): void{console.debug('Assets loading started');}create(): void {console.debug('Assets loading completed');this.game.state.start('main'); // Switch to `main` state after all images are loaded}}

As stated above, PreloaderState we need to load the resources for our game (of course, if the game has a lot of resources, they should be loaded before their respective stats, and in preloader should only load the critical ones. But in our case we will load all resources before the game starts).

Notice that preload(): void will be called first, and create(): void after all the resources have been loaded.

Generally speaking, the breakdown into stats is pretty subjective. You can add any number of them ( Prepreloader , Prepreloader etc.), but in my experience you need at least 3staites :

  • BootState – to initialize and output build information.
  • PreloaderState – for downloading resources.
  • MainState – for the main loop of the game.

Fourth , connect these stats in src/index.ts :

// ...import BootState from './states/boot.state';import PreloaderState from './states/preloader.state';import MainState from './states/main.state';// ...export default class App extends Phaser.Game {constructor(config: Phaser.IGameConfig) {super(config);// Registering game statesthis.state.add('boot', BootState);this.state.add('preloader', PreloaderState);this.state.add('main', MainState);this.state.start('boot');// Initialize and release the 'boot' state }}// ...

Notice that we substituted This.state.start('main'); to this.state.start('boot');

Resource Download

Now that the rebuild is complete, let’s load the necessary resources for our game. We will do this by calling the method this.game.load within the method preload(): void ( PreloaderState ).

Each state has a link to App to which it is connected : this.game

Phaser itself will call this method when our game starts and will load everything we defined in it.

Phaser loads resources in its own, magical, way via Phaser.Loader You don’t need to pass in this.game.load callbacks or Promis, it tracks the load itself.

Let’s add in src/states/preloader.state.ts the following code :

'use strict';/** Imports */import State from './state';//Webpack will replace such require's with URLs before these images, andput the // images themselves in the `dist/asserts/images' folder.// And the code below, it will replace something like this:// 'const skyImage = '/assets/images/sky.png';`// (For more information about such "substitutions" of the Webpack, see the documentation).const skyImage = require('assets/images/sky.png');const platformImage = require('assets/images/platform.png');const starImage = require('assets/images/star.png');const dudeImage = require('assets/images/dude.png');export default class PreloaderState extends State {preload(): void {console.debug('Assets loading started');this.game.load.image('sky', skyImage); // <=this.game.load.image('platform', platformImage); // <=this.game.load.image('star', starImage); // <=this.game.load.spritesheet('dude', dudeImage, 32, 48); // <=}create(): void {console.debug('Assets loading completed');this.game.state.start('main'); // Switching to `main' state after loading all images}}

The resources themselves are at Github repositories in the directory assets/images , you also need to add them to your local project, in the same directory ( assets/images ).

On lines 20-23 we load 4resources: 3 images and one sprite. Note the first argument (key) this.game.load.image() and this.game.load.spritesheet() , this is the identifier we will use later for accessing this resource (the key can be any string).

3 and 4 argument at this.game.load.spritesheet() – is the height and width of one image in the sprite sheet.

Creation of sprite

To add a sprite to our game, we need to add the following code to create(): void ( MainState ):

'use strict';/** Imports */import State from './state';// Main state of the gameexport default class MainState extends State {create(): void {this.game.add.sprite(0, 0, 'star'); // <=}}

Now, in the upper left corner of your browser, you should see a yellow asterisk :

Creating your first gameon Phaser.Part 2- Loading Resources

First argument this.game.add.sprite() – axis x , the second is the axis y , and the third is the same key that we specified when loading the image.

The order in which items are drawn on the screen corresponds to the order in which they are created. So if you want to add a background behind the star, you need to create this sprite first, before the star sprite.

Actually, you have the option of setting the Z index manually and sorting elements in the game world by it, but initially Phaser does this for you, setting each subsequent element Z index + 1.

Finally, let’s add a little more stars :

'use strict';/** Imports */import State from './state';// MainStateexport default class MainState extends State {create():void {const map = ['X X XX XXX XXX XXX ', 'X X X X X X X X X', 'XXXX XXXX XXXX XXXX ', 'X X X X X X X XX ', 'X X X X X X X X X X'].map((line) => line.split('')); // Break lines into separate characters// bypass all lines and symbolsmap.forEach((line, y) => line.forEach((char, x) => {if (char !== 'X') {return;}// If the symbol corresponds to `X`, draw a star instead.// 24 - image width.// 22 - height.this.game.add.sprite(x * 24, y * 22, 'star');}));}}

And we get this :

Creating your first gameon Phaser.Part 2- Loading Resources

At this point the lesson came to an end.

Github Repo : https://github.com/SuperPaintman/phaser-typescript-tutorial

To the content

You may also like