我正在创建一种“太空侵略者”游戏,在将分数从WorldScene传递到GameOverScene方面确实存在问题。
我已经尝试使用init:function()传递数据,但是我可能做错了事...
我正在使用Phaser 3。
我的一些WorldScene:
constructor() {
super( { key: 'WorldScene'} );
}
preload()
{
}
create()
{
var score = 0;
(...)
//a scene comeca de novo
//this.scene.restart();
this.scene.start('GameOverScene', {score_n: this.score} );
}, [], this);
还有我在game.js中的GameOverScene
Extends: Phaser.Scene,
initialize:
function GameOverScene ()
{
Phaser.Scene.call(this, { key: 'GameOverScene' });
},
init: function (data)
{
console.log('init', data);
this.scoreFinal = data.score_n;
},
preload: function ()
{
//background inicial
this.load.image('back_menu', 'assets/img_espaco.png');
},
create: function (data)
{
let backg = this.add.sprite(0, 0, 'back_menu');
backg.setOrigin(0, 0);
//texto do game over
gameOver_text = this.add.text(320, 150, 'Game Over', { fontSize: '70px', fill: '#FF0000' });
gameOver_text.setOrigin(0.5);
//score
scoreFinal_txt = this.add.text(320, 210, 'Pontuação Final: '+ this.scoreFinal, { fontSize: '20px', fill: '#FFF' });
scoreFinal_txt.setOrigin(0.5);
//botao de recomeçar
bt_novo = this.add.text(320, 260, 'Voltar ao Inicio', { fontSize: '30px', color: '#ffffff' }).setInteractive();
bt_novo.setOrigin(0.5);
//se o botao for carregado começa o jogo
bt_novo.on('pointerdown', function (event) { this.scene.start('MenuScene'); }, this );
bt_novo.on('pointerover', function (event) { bt_novo.setStyle({ fill: '#ff0'}); } )
bt_novo.on('pointerout', function (event) { bt_novo.setStyle({ fill: '#ffffff'}); } )
},
}); ```
My scoreFinal_txt shows: "Pontuaçao Final: undefined"
答案 0 :(得分:0)
您可以通过this.scene.start(key, data)
的第二个参数传递其他场景数据
class IntroScene extends Phaser.Scene {
constructor() {
super({
key: 'intro'
});
}
create() {
const btn = this.add.text(20, 20, 'Hello', { fontSize: '30px', color: '#ffffff' }).setInteractive();
btn.addListener('pointerup', () => {
console.log('game started click');
this.scene.start('game', 666); // second argument enables passing data
});
}
}
class GameScene extends Phaser.Scene {
constructor() {
super({
key: 'game'
});
}
/**
* @param data passed to scene at startup
*/
create(data) {
console.log('game started', data);
this.add.text(20, 20, `Game ${data}`, { fontSize: '30px', color: '#ffffff' });
}
}