2015-09-26 111 views
0

我正在創建我的第一個Phaser遊戲作爲chromecast接收器應用程序,我在使用我的代碼時遇到了一些麻煩。Phaser.State未初始化

我有下面的代碼工作:

class TNSeconds { 

game: Phaser.Game; 


constructor() { 
    this.game = new Phaser.Game(window.innerWidth * window.devicePixelRatio -20, window.innerHeight * window.devicePixelRatio -20, Phaser.CANVAS, 'content', { preload: this.preload, create: this.create }); 
} 

preload() { 
    this.game.load.image('BG', 'bg.png'); 
    this.game.load.atlas("Atlas", "atlas.png", "atlas.json"); 
} 

create() { 
    var background= this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'BG'); 
    logo.anchor.setTo(0.5, 0.5); 
    this.game.add.sprite(320, 100, "Atlas", "dron1", this.game.world); 
} 
} 


window.onload =() => { 
    var game = new TNSeconds(); 

}; 

不過我下面的教程和例子奠定了作爲這樣的代碼:

class Game extends Phaser.Game { 

constructor() { 
    // init game 
    super(window.innerWidth * window.devicePixelRatio - 20, window.innerHeight * window.devicePixelRatio - 20, Phaser.CANVAS, 'content', State); 
} 


} 

class State extends Phaser.State { 
    preload() { 
     this.game.load.image('BG', 'bg.png'); 
     this.game.load.atlas("Atlas", "atlas.png", "atlas.json"); 
    } 
create() { 

    this.add.image(0, 0, "BG"); 

    this.add.sprite(320, 100, "Atlas", "dron1", this.world); 

} 

} 

window.onload =() => { 
    var game = new Game(); 

}; 

的教程代碼看起來更乾淨,只是爲了翻譯教程,我希望類似地實現我的代碼,問題似乎是State類沒有初始化,有沒有人可以爲我解釋這一點。

我知道教程代碼是使用this.add.image我在使用this.game.add.sprite這不是問題。

回答

2

試着這麼做:

game.ts

module Castlevania { 

    export class Game extends Phaser.Game { 

     constructor() { 

      super(800, 600, Phaser.AUTO, 'content', null); 

      this.state.add('Boot', Boot, false); 
      this.state.add('Preloader', Preloader, false); 
      this.state.add('MainMenu', MainMenu, false); 
      this.state.add('Level1', Level1, false); 

      this.state.start('Boot'); 
     } 
    } 
} 

boot.ts

module Castlevania { 

    export class Boot extends Phaser.State { 

     preload() { 

      this.load.image('preloadBar', 'assets/loader.png'); 

     } 

     create() { 

      // Unless you specifically need to support multitouch I would recommend setting this to 1 
      this.input.maxPointers = 1; 

      // Phaser will automatically pause if the browser tab the game is in loses focus. You can disable that here: 
      this.stage.disableVisibilityChange = true; 

      if (this.game.device.desktop) { 
       // If you have any desktop specific settings, they can go in here 
       this.stage.scale.pageAlignHorizontally = true; 
      } 
      else { 
       // Same goes for mobile settings. 
      } 

      this.game.state.start('Preloader', true, false); 
     } 
    } 
} 

你可以找到一個完全工作的例子here

+0

我試圖按照這個例子,甚至使用不到6個月前更新的代碼,我發佈了這些問題:https://stackoverflow.com/questions/32802777/打字稿擴展關鍵字不工作 – Johntk

+0

我解決了我鏈接的其他帖子上的問題,感謝您的意見。 – Johntk