Home > database >  Function definition does not work in phaser 3
Function definition does not work in phaser 3

Time:12-20

I'm an old programmer but new to phaser. Maybe my question may sound simple. The tween works in the object I defined with the code below.

function preload ()
{
    this.load.image('back', 'BACK.png');
}

function create () {

    let back = this.add.sprite(100, 100, 'back')
        .setInteractive().setScale(0.2);

    this.tweens.add({
        targets: back,
        x: {value: 100, duration: 1500, ease: 'Power2'},
        y: {value: 500, duration: 500, delay: 150}
    });
}

But I want to define it inside the function and callback. Like the following:

    function preload ()
    {
        this.load.image('back', 'BACK.png');
    }

    function create () {
        Gotween();
    }

    function Gotween (){
        let back = this.add.sprite(100, 100, 'back')
        .setInteractive().setScale(0.2);

    this.tweens.add({
        targets: back,
        x: {value: 100, duration: 1500, ease: 'Power2'},
        y: {value: 500, duration: 500, delay: 150}
    });
}

But I get the error like that:

"Uncaught TypeError: Cannot read properties of undefined (reading 'sprite')".

Is there something I don't know about Phaser? What are your suggestions? Thanks,

I think tweens should work inside the function as well.

CodePudding user response:

Well the issue is, that the this object of the Gotween function is not the current "scene" ( the this object is not pointing to the scene * ), easy solution is to pass the scene into the function

...
function create () {
    Gotween(this);         // <- pass current scene context
}
...
function Gotween (scene){  // <- parameter "scene"
    let back = scene.add.sprite(100, 100, 'back'); // <- instead of "this"

    scene.tweens.add({     // <- instead of "this"
        ... 
    });
}

Or a "nicer" solution, would be to add the function to the scene (there are a few ways)

This is my favorit:

  1. add function to the game config, under the property scene -> extend

    // in the game config
    var config = {
        type: Phaser.AUTO,
        width: ...
        scene:{
            extend: {
                Gotween: Gotween // <- function added to the scene
            },
            create: create,
            ...
        }
    };
    ....
    
  2. Use the function as a part of the scene this.Gotween().
    like this you can use this.add.sprite(...) and others, in your function.

    function create () {
       ...
       this.Gotween();    // <- call as "method" of the scene
       ...
    }
    
    ...
    
    function Gotween (){
       let back = this.add.sprite(100, 100, 'back'); // <- access to 'this'
       ...
    }
    

* If you want to deep dive into the whole javascript this/function/inheritance topic you can checkout this link to a mdn advanced tutorial

  • Related