Search code examples
javascriptcordovacordova-pluginsphaser-framework

Phaser shake detection


I was playing with phaserjs and cordova and i'm stuck in something probably trivial. It's more general javascript question than phaser but i couldn't find any answer.

I'm using Cordova-plugin-shake for shake detection and it works great. What i would like to do, is to change some sprites 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;
    },
[...]
  
};

The problem is that onShake is passed by value, right? So i don't have access to either setCapacity() or hand. How can i avoid it? Are there any tutorials/examples like that where i can read?

Thanks for your time and sorry for such a trivial question but i'm still very new to js.


Solution

  • You should be able to do this

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

    The bind method is used to attach a context to a new function

    Or if you can't use bind, you can make a closure

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