移相器抖动检测

Phaser shake detection

我正在玩 Phaserjs 和 Cordova,但我被困在一些可能微不足道的事情中。这是比 Phaser 更笼统的 javascript 问题,但我找不到任何答案。

我正在使用 Cordova-plugin-shake 进行抖动检测,效果很好。我想做的是改变一些精灵 onShake()。

Test.Game.prototype = {
 create: function() {
        this.hand = this.game.add.sprite(this.game.world.centerX-36, 27, 'hand');
        this.hand.animations.add('squeeze',[0,1,2,3,4,5,6,5,4,3,2,1,0]);
        this.hand.animations.add('shake',[8,9,10,11,12,13,14,15,16,17,17,8,9,8]);
        this.healthBar = this.game.add.sprite(260, 18, 'utils');
        this.setCapacity(4);
        shake.startWatch(this.onShake, 40);
      },
     onShake: function(){
        console.log("shaked");
        this.hand.animations.play('shake', 60, false);
        this.setCapacity(Math.floor(Math.random() * (MAX_CAPACITY - MIN_CAPACITY + 1)) +  MIN_CAPACITY);
      },
     setCapacity: function(capacity){
        this.healthBar.prevCap = capacity;
        this.healthBar.inCapacity = capacity;
        this.healthBar.capacity = capacity;
        var cropRect = new Phaser.Rectangle(0, 0, healthBarWidth, this.healthBar.height);
        this.healthBar.crop(cropRect);
        this.healthBar.prevWidth = healthBarWidth;
    },
[...]
  
};

问题是onShake是按值传递的吧?所以我无法访问 setCapacity() 或手。我怎样才能避免它?有没有类似的tutorials/examples我可以看的?

感谢您的宝贵时间,很抱歉提出这样一个微不足道的问题,但我对 js 还是很陌生。

你应该可以做到这一点

shake.startWatch(this.onShake.bind(this), 40);

bind 方法用于将上下文附加到新函数

或者如果不能使用bind,可以做一个闭包

 shake.startWatch((function(game){
     return function(){
         game.onShake();
     };
 })(this), 40);