2015-10-23 67 views
2

我正在玩phaserjs和cordova,我被困在可能微不足道的東西。這是比移相器更一般的JavaScript問題,但我找不到任何答案。移相器抖動檢測

我使用Cordova-plugin-shake進行抖動檢測,效果很好。我想要做的是改變Shake()上的一些精靈。

Test.Game.prototype = { 
 
\t 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()或手。我如何避免它?是否有任何教程/例子可以閱讀?

感謝您的時間和對這樣一個微不足道的問題抱歉,但我仍然是非常新的js。

+0

「Phaser」的標記說明告訴我,它是Java 7中的一個工具。該標記與JavaScript問題有什麼關係? – feeela

+0

不,它是一個JavaScript遊戲框架phaser.js。 –

+0

然後那是錯誤的標籤 - 我將其更改爲JS框架標籤。 – feeela

回答

3

你應該能夠做到這一點

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

bind方法用於上下文附加到新的功能

或者,如果你不能使用綁定,就可以使一個封閉

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

綁定工作正常!謝謝你讓我知道關閉! –