如何使用phaser框架在html5中实现设备定向

how to implement device orientation in html5 with phaser framework

本文关键字:实现 html5 何使用 phaser 框架      更新时间:2023-09-26

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

预加载:函数(){

    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;

},`

这看起来像是一个范围问题。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;
}