相位抖动检测

Phaser shake detection

本文关键字:检测 抖动      更新时间:2023-09-26

我在玩phaserjs和cordova,我被困在一些可能微不足道的东西。这是一个比相位器更普遍的javascript问题,但我找不到任何答案。

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

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()或hand。我怎样才能避免呢?有没有像这样的教程/例子,我可以阅读?

谢谢你的时间,很抱歉这样一个微不足道的问题,但我仍然是非常新的js。

你应该能够做到这一点

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

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

如果你不能使用bind,你可以创建一个闭包

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