Scene e Game Loop
Cos’è una Scene?
In Phaser 3, una Scene è un contenitore per la logica del gioco. Ogni livello, menu o schermata è tipicamente una Scene separata.
Struttura di una Scene
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
preload() {
// Carica assets
this.load.image('player', 'assets/player.png');
}
create() {
// Inizializza oggetti di gioco
this.player = this.add.sprite(400, 300, 'player');
}
update(time, delta) {
// Logica di gioco eseguita ogni frame
// time: tempo totale dall'avvio
// delta: millisecondi dall'ultimo frame
}
}
Metodi del Lifecycle
preload()
Carica tutti gli assets necessari. Viene chiamato una sola volta prima di create().
preload() {
this.load.image('background', 'assets/bg.png');
this.load.spritesheet('player', 'assets/player.png', {
frameWidth: 32,
frameHeight: 48
});
this.load.audio('jump', 'assets/jump.mp3');
}
create()
Inizializza la scena. Viene chiamato una volta dopo preload().
create() {
// Aggiungi background
this.add.image(400, 300, 'background');
// Crea player
this.player = this.physics.add.sprite(100, 450, 'player');
// Configura fisica
this.player.setBounce(0.2);
this.player.setCollideWorldBounds(true);
// Crea animazioni
this.anims.create({
key: 'walk',
frames: this.anims.generateFrameNumbers('player', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
}
update(time, delta)
Eseguito ogni frame. Qui va la logica di gioco.
update(time, delta) {
const cursors = this.input.keyboard.createCursorKeys();
if (cursors.left.isDown) {
this.player.setVelocityX(-160);
this.player.anims.play('walk', true);
} else if (cursors.right.isDown) {
this.player.setVelocityX(160);
this.player.anims.play('walk', true);
} else {
this.player.setVelocityX(0);
this.player.anims.stop();
}
if (cursors.up.isDown && this.player.body.touching.down) {
this.player.setVelocityY(-330);
}
}
Gestire Multiple Scene
Avviare Scene
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
scene: [MenuScene, GameScene, GameOverScene]
};
const game = new Phaser.Game(config);
Cambiare Scene
// Ferma la scena corrente e avvia un'altra
this.scene.start('GameScene');
// Pausa la scena corrente
this.scene.pause();
// Riprendi una scena in pausa
this.scene.resume();
// Esegui scene in parallelo
this.scene.launch('UIScene');
// Ferma una scena parallela
this.scene.stop('UIScene');
Passare Dati tra Scene
// Avvia una scena con dati
this.scene.start('GameScene', { level: 2, score: 1000 });
// Ricevi dati nella nuova scena
class GameScene extends Phaser.Scene {
init(data) {
this.level = data.level;
this.score = data.score;
}
}
Game Loop
Il game loop di Phaser gestisce automaticamente:
- Input: Processa eventi di input
- Update: Chiama
update()su tutte le scene attive - Physics: Aggiorna il sistema fisico
- Render: Disegna tutto sullo schermo
Frame Rate
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
fps: {
target: 60,
forceSetTimeOut: false
},
scene: GameScene
};
Delta Time
Usa delta per rendere il movimento indipendente dal framerate:
update(time, delta) {
// Movimento dipendente dal framerate (SBAGLIATO)
this.player.x += 5;
// Movimento indipendente dal framerate (CORRETTO)
const speed = 200; // pixel al secondo
this.player.x += speed * (delta / 1000);
}
Scene Manager
Accedi al Scene Manager per controllo avanzato:
// Ottieni riferimento ad altra scena
const gameScene = this.scene.get('GameScene');
// Controlla se una scena è attiva
if (this.scene.isActive('GameScene')) {
// ...
}
// Ottieni tutte le scene
const scenes = this.scene.manager.scenes;
Best Practices
- Una responsabilità per scena: Menu, Game, GameOver, ecc.
- Usa init() per dati: Ricevi dati da altre scene in
init() - Pulisci in shutdown(): Rimuovi event listener e timer
- Scene parallele per UI: Usa
launch()per HUD persistente - Delta time: Usa sempre
deltaper movimento fluido
Esempio Completo
class MenuScene extends Phaser.Scene {
constructor() {
super({ key: 'MenuScene' });
}
create() {
const startButton = this.add.text(400, 300, 'Start Game', {
fontSize: '32px',
fill: '#fff'
}).setOrigin(0.5).setInteractive();
startButton.on('pointerdown', () => {
this.scene.start('GameScene', { level: 1 });
});
}
}
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
init(data) {
this.currentLevel = data.level;
}
create() {
this.add.text(10, 10, `Level ${this.currentLevel}`, {
fontSize: '24px',
fill: '#fff'
});
// Avvia UI scene in parallelo
this.scene.launch('UIScene');
}
update(time, delta) {
// Game logic
}
}
class UIScene extends Phaser.Scene {
constructor() {
super({ key: 'UIScene' });
}
create() {
this.scoreText = this.add.text(10, 10, 'Score: 0', {
fontSize: '20px',
fill: '#fff'
});
}
}
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
scene: [MenuScene, GameScene, UIScene]
};
new Phaser.Game(config);
Conclusione
Le Scene sono il cuore di ogni gioco Phaser. Comprendere il lifecycle e il game loop è fondamentale per creare giochi fluidi e ben strutturati.
