How to access gameObjects and variables from another function?

How do I access my player from another function?

In my create I have:

this.player = this.physics.add.sprite(width/2, height/2, 'player');
var isMoving = false;

this.input.on('pointerdown', movePlayer);

and in movePlayer:

function movePlayer(pointer)
{alert(this.isMoving);alert(this.player);
    if(!isMoving)
    {
        isMoving = true;
        if(pointer.downX > width/2)
            this.player.setVelocityX(100);alert();
        else if(pointer.downX < width/2)
            this.player.setVelocityX(-100);
    }
}

Both the alerts give me undefined and the player doesnt move. I know there’s something wrong with the way I’m accessing it but I don’t know what because in the update function

this.player.setVelocityX(100);

works fine.

How do I know what is “this” in the create function?
And also why do we write
this.player = this.physics.add.sprite()
and why not
player = this.physics.add.sprite()

You have to go back to the basics, variable scope, contexts

1 Like

Thanks I’ll have a look at that.

Good Morning, I am new to Phaser also. I also struggled with “this” . So I use this:

console.log(this);

and it helps me learn what my current scope is at any given point. Typically I find out that “this” is referring to my current scene.

https://github.com/samme/phaser3-faq/wiki#how-do-i-use-this-in-a-scene

2 Likes