问题
My question is specific about Phaser game engine
So I have a game with a few states and each state is defined like:
var myGame = {};
myGame.Boot = function (game) {
};
myGame.Boot.prototype = {
init: function () {
//some init
},
create: function () {
//this.scale.scaleMode
this.state.start('Preloader');
}
};
and a game is defined like:
var game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, 'main');
game.state.add('Boot', myGame.Boot);
game.state.add('Preloader', myGame.Preloader);
game.state.add('MainMenu', myGame.MainMenu);
Normal, simple, standard. All good (so far).
Here is how I'm defining a music in my 'Preloader' (same as here):
fx = game.add.audio('sfx');
fx.allowMultiple = true;
fx.addMarker('alien death', 1, 1.0);
fx.addMarker('boss hit', 3, 0.5);
fx.addMarker('escape', 4, 3.2);
fx.addMarker('meow', 8, 0.5);
fx.addMarker('numkey', 9, 0.1);
this.sound.setDecodedCallback(
[gg.fx],
this.start, this
);
where fx is a global variable. And then if I need to play a music I do
fx.play(button.name);
The code works, but I have to always keep this global var (or pass it to every state where I need a music).
So I have a few questions:
- I don't like global variables. Is there a better way of doing that? I'm planing to have a good amount of effects, I'd like to have a simple way to manage them.
- If I'm not using a global var and calling a code like this.sound.play("name") it says that file not in the cache. Is there a way to add it to global cache? Is it a bad idea?
Thanks!
回答1:
- Global vars:
You could actually define these on myGame
. While it uses a different way of defining these, take a look at the Full Screen Mobile Template that's part of the Phaser codebase itself. The creator of Phaser actually recommended this on their forums for declaring 'global' variables.
That gives you something like this:
myGame.fx = game.add.audio('sfx');
// ...
- Global cache:
Good question. The only thing I've found is breaking the MP3 files up and loading them into the cache individually. In that way your cache has an object with that name/key.
But if you add these to your myGame
object, you should be able to keep your audio in a single file.
来源:https://stackoverflow.com/questions/42912021/passing-a-music-object-between-states-in-a-phaser-game-engine