Jump to content

How an object attribute functions in phaser know other functions


Recommended Posts

I built a simple game using phaser, but didn't use multiple game states. The game had only one screen and no states! It was all poorly done. So now I'm learning game states.

In this code snippet, taken from a phaser game https://github.com/alexdantas/ludum-dare-29/blob/master/js/states/play.js, we have, for example, a line consisting of this.game.camera.setBoundsToWorld().

I know how this works, but i'm having trouble knowing who is this here. I know this in OOP refers to the "owner" of the function, but in this case, who is it?

Another doubt I'm struggling with is, where does the .game.camera.setBoundsToWorld() comes from? Is it from when Phaser initializes a new state? When it start a new state, does it create a new "main state", which in this case is what the "this" refers to, and add attributes/methods to it? Like this game.camera.setBoundsToWorld() method?

function Play() {}

Play.prototype = {
	create: function() {
		this.game.stage.backgroundColor = '#000';
		// initialize game variables
		this.cash = 0;
		this.chunkGroup = this.game.add.group();
		this.nextChunkY = 0;
		this.game.world.bounds.x = 0;
		this.game.world.bounds.height = 1024;
		this.lastChunkIndex = 0;
		this.tephra = this.game.add.group();
		this.rocks = this.game.add.group();
		this.gems = this.game.add.group();
		this.carrots = this.game.add.group();
		this.lastChunk = null;
		this.chunkIndex = 0;


Link to comment
Share on other sites

If you want to see what 'this' is actually referring to at a particular point, just do 'console.log(this);'.

In your code, the Play state is the "owner" of the create function, so 'this' refers to the currently running state. Each state has a property 'game', which is a reference to the Phaser game object. In general, you should be trying to add things to the state itself, rather than to the game object.

I would recommend removing the '.game' from 'this.game.physics.startSystem(Phaser.Physics.ARCADE);', so that the physics system is started for this state only. Every time you are doing 'this.game.add.group()' is also adding those groups to the game object, not to the state.

Link to comment
Share on other sites


  • Recently Browsing   0 members

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