Phaser 3 ES6 disableBody and keyboard input

Hello, I am new to both Javascript and Phaser.
I’m learning to build something with ES6 format without NodeJS

Here’s how my code looks like:

var space;

class gameScene extends Phaser.Scene 
{
    constructor (config) 
    {
        super({key:"game"});
    }

    create ()  
    {
     bushes = this.physics.add.staticGroup();
    bushes.create(50, 425, "bush");  
     bushes.create(200, 425, "bush");
      bushes.create(900, 425, "bush");
      bushes.create(500, 425, "bush");

         berry = this.physics.add.staticGroup();
         berry.create(50, 425, "berry");  
         berry.create(200, 425, "berry");
         berry.create(900, 425, "berry");
         berry.create(500, 425, "berry");

          //code for player goes here
        this.physics.add.overlap(player, berry, this.collectBerry());
}
update()
{
         space = this.input.keyboard.addKey("SPACE");

}

collectBerry (player, berry)
    {
        berry.disableBody(true, true);
        if(space.isDown)
        {
        infoTxt.setText(" berry acquired.");
        }
    }

Basically the idea is when the player walks up to the berry and press space the berry will disappear and player gets some berry.
I get 2 errors when commenting out parts of collectBerry()

Cannot read property 'isDown' of undefined

and

Cannot read property 'disableBody' of undefined

I have tried adding this. but it still doesn’t work.
Does anybody have idea of what I did wrong?

Hi,

Change this

to

this.physics.add.overlap(player, berry, this.collectBerry);

Hopefully this fixes it :slight_smile:

When a function takes a function as a parameter, you pass it by the name, not using the () as that is telling calling the function to execute, and what you really want is for the function to be called when an overlap happens, and not right when you add it to the function overlap.
Hope this helps also clarify a bit as to why that happens.

As a side note, for ES6 code I believe you want to start using “const” and “let” and not “var” anymore.

This should be in create(), not update().

Thank you!
Do you have any idea how do I fix

 Cannot read property 'isDown' of undefined 

Apparently I have the same issue with infoTxt.setText

I actually tried it both way before posting. Neither of them worked with same error.