【问题标题】:Phaser Sprite body returning undefined on input onPhaser Sprite 主体在输入时返回未定义
【发布时间】:2022-09-28 19:30:34
【问题描述】:

每当我单击鼠标时,我都会尝试轻弹,但input.on 上的变量在单击鼠标时返回 undefined 这里是 sn-p。 Phaser对我来说是新的

    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;
    }

    标签: angular typescript phaser-framework


    【解决方案1】:

    问题是,你必须通过正确的上下文,到on eventlistener。这样它就可以工作了。这是link to the documentation

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

    附:或者你可以使用箭头函数,如果您不想传递上下文。我不建议这样做,只是为了展示一个替代选项,很多人很高兴知道,因为很多人都使用这种编码方式。 这里是documentation for arrow functions的链接

    换句话说,这也有效:

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

    【讨论】:

    • 哇,非常感谢你,这不是我自己注册的 udemy 教程。
    • @ralphy 确定。 between.:如果您使用箭头函数,则不必使用上下文。
    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多