1

我正在尝试使用使用设备方向 API 的移相器框架制作一个简单的游戏,我尝试这样做,但移动没有完成。这是代码`

预加载:函数(){

    game.stage.backgroundColor = '#64FE2E';
    game.load.image('gau','assets/ball.png');
},

create: function() { 

    this.ball = this.game.add.sprite(100,245, 'gau');

},

update: function() {
    // Function called 60 times per second
    if(this.ball.inWorld == false)
       this.restart_game();
        keys = this.game.input.keyboard.createCursorKeys();
    window.addEventListener("deviceorientation", this.handleOrientation, true);
},

handleOrientation: function(e) {
var x = e.gamma; // range [-90,90]
var y = e.beta;  // range [-180,180]
this.ball.body.velocity.x -= x*2;
this.ball.body.velocity.y -= y*4;

}, `

4

1 回答 1

1

它看起来像一个范围问题。handleOrientation 中的“this”将引用“window”。

window.addEventListener("deviceorientation", this.handleOrientation, true);

handleOrientation: function(e) {
  var x = e.gamma; // range [-90,90]
  var y = e.beta;  // range [-180,180]
  // looking for reference to ball on the window object
  this.ball.body.velocity.x -= x*2;
  this.ball.body.velocity.y -= y*4;
}

解决此问题的一种方法是将handleOrientation方法“绑定”到当前范围,如下所示:

window.addEventListener("deviceorientation", this.handleOrientation.bind(this), true);

handleOrientation: function(e) {
  var x = e.gamma; // range [-90,90]
  var y = e.beta;  // range [-180,180]
  // this now refers to the game object
  this.ball.body.velocity.x -= x*2;
  this.ball.body.velocity.y -= y*4;
}
于 2014-10-22T21:43:17.657 回答