Home > Software engineering >  Phaser Sprite body returning undefined on input on
Phaser Sprite body returning undefined on input on

Time:09-26

I am trying to flick whenever i click the mouse but the variable on input.on is returning undefined upon clicking the mouse down here is the snippet. Phaser is new to me

    w : number;
    h : number;
    velocity:number;
    sprite = null;
    totalDelta = null;

    constructor() {
        super({ key: 'Init' });
    }

    preload(){
      this.w = Number(this.game.config.width);
      this.h = Number(this.game.config.height);
      this.velocity = Number(this.game.config.physics.arcade.gravity.y);
      this.createBG();
    }


    createBG(){
      this.add.image(0,0,'background').setOrigin(0);
    }

    createSprite(){
      var x = this.w * 0.1; 
      this.sprite = this.physics.add.sprite(x ,this.h/2,'sprite').setOrigin(0);
    }

    create(){
      this.createSprite();
      this.input.on("pointerdown",this.flick);
    }

    flick(){
      this.sprite.body.velocity.y = -this.velocity;
    }

CodePudding user response:

The problem is, that you have to pass the correct context, to the on eventlistener. So that it works. Here is the link to the documentation

// pass the context, as third parameter
this.input.on("pointerdown", this.flick, this);

P.s.: or you can use a arrow function, if you don't want to pass the context. I don't recommend doing this, but just to show an alternative option. here is the documentation to arrow functions

this.input.on("pointerdown", () => this.flick());
  • Related