Jump to content

Phaser Global Objs


Recommended Posts


Iam confused a bit to the global objects of phaser . Lets say in a browser , when we type this we know that it refers to windows . Iam follow a phaser udemy series , and iam confused on the 'this' keyword .


var game = new Phaser.Game(640, 360, Phaser.Auto);

var gameState = {
    preload: function(){
    create: function(){
        this.background = this.game.add.sprite(0,0, 'background');
    update: function(){

My first question is, from where does the new gameState obj inherits its methods and properties, and where does the gameState belong to ? ? Is there any tutorial of explaining the global objects in phaser and the hierarchy ? Its a stupid question but iam beginner and iam  confused :D 

Link to comment
Share on other sites

It's okay, this stuff is confusing.

Phaser declares a global object named "Phaser" more or less like this: "window.Phaser = window.Phaser || {};". That means "assign to the Phaser property on window the already existing value of window.Phaser. If there's nothing there, assign an empty object to it instead." That's a good way of making it assign an empty object if there's not one already. You'll see this everywhere in JavaScript code.

After that, there's code in the Phaser library that keeps adding functions and objects to this top-level thing: "window.Phaser.State = ..." and "window.Phaser.Sprite = ...". That builds up all the classes you have available to you in Phaser.

Your declaration of "gameState" is called an object primitive. It's a great way to make objects in JavaScript. You are the one defining those functions on it (i.e. preload, update, etc.), not Phaser. This object eventually gets passed to the Phaser StateManager through a call to add: https://github.com/photonstorm/phaser/blob/1bad8811396ba1062ab3dcdcbbf6a9d0d7cd5391/v2/src/core/StateManager.js#L193

Eventually, the StateManager "fills in the blanks" and sets a bunch of useful properties on the object you created: https://github.com/photonstorm/phaser/blob/1bad8811396ba1062ab3dcdcbbf6a9d0d7cd5391/v2/src/core/StateManager.js#L459

It then uses those functions you defined to run your game: https://github.com/photonstorm/phaser/blob/1bad8811396ba1062ab3dcdcbbf6a9d0d7cd5391/v2/src/core/StateManager.js#L530

The best way to learn the hierarchy is to read the docs: http://phaser.io/docs/2.6.2/index

The front page has a column, "via". That is the name of the property on the game and, usually, the state objects: game.add, game.make, all those things. Check it out.

Link to comment
Share on other sites

Within the standard state callbacks (init/create/update…), this is the current state. It has a reference to the game (this.game) and most of the important game objects, but it's distinct from game.

--- game
+++ state
@@ -1,53 +1,19 @@


Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...