Certainly! Let's walk through adding the OutGhostHouseScene to your Phaser game. This new scene will represent the outside of the ghost house and will maintain the ghost's state (such as position and whether the weapon is picked up) when transitioning between scenes.
Overview of Steps
- Preload New Assets: Ensure that any new assets required for the
OutGhostHouseScene are loaded in the PreloadScene.
- Define
OutGhostHouseScene: Create the new scene, mirroring the InGhostHouseScene in functionality but with an outdoor environment.
- Handle State Management: Maintain the ghost's state (position, model, weapon status) when transitioning between scenes.
- Update Scene Transition Logic: Modify the
openDoor method in InGhostHouseScene to transition to the new scene, passing necessary state data.
- Update Phaser Configuration: Add the new scene to the Phaser game configuration.
Let's implement each of these steps in detail.
1. Preload New Assets
First, ensure that any new assets required for the OutGhostHouseScene are loaded during the preload phase. For example, you'll need a background image for the outside of the ghost house. Let's assume you have an image named ghost-house-outside.png.
Update the PreloadScene as follows:
// Inside PreloadScene's preload() method
this.load.image('ghostHouseOutside', 'assets/images/ghost-house-outside.png');
Make sure to place this line among other this.load.image calls in the preload method.
2. Define OutGhostHouseScene
Next, create the OutGhostHouseScene class. This scene will be similar to InGhostHouseScene but will display the outside environment.
// Out Ghost House Scene: Shows the outside of the ghost house and allows user interaction with the ghost
class OutGhostHouseScene extends Phaser.Scene {
constructor() {
super({ key: 'OutGhostHouseScene' });
}
init(data) {
// Receive ghost state from the previous scene
this.ghostState = data.ghostState || {
x: 260,
y: 340,
angle: 0,
scale: 0.25,
weaponPicked: false,
texture: 'ghost'
};
}
create() {
// Add background image for outside
this.add.image(320, 240, 'ghostHouseOutside').setDisplaySize(640, 480);
// Add ghost based on the received state
this.ghost = this.add.image(this.ghostState.x, this.ghostState.y, this.ghostState.texture)
.setOrigin(0.5, 0.5)
.setScale(this.ghostState.scale)
.setAngle(this.ghostState.angle);
// If the weapon is picked, hide it
if (this.ghostState.weaponPicked) {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85)
.setVisible(false);
} else {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85);
}
// Add interaction buttons similar to InGhostHouseScene
// For brevity, we'll add only a "Return Inside" button to go back to InGhostHouseScene
this.returnButton = this.add.text(320, 450, 'Return Inside', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.on('pointerdown', () => this.returnInside());
// Keyboard controls for movement
this.cursors = this.input.keyboard.createCursorKeys();
// Left and Right buttons for touch input
this.leftButton = this.add.image(100, 400, 'leftButton').setInteractive();
this.rightButton = this.add.image(540, 400, 'rightButton').setInteractive();
// Scale and transparency for the buttons
this.leftButton.setScale(0.5).setAlpha(0.7);
this.rightButton.setScale(0.5).setAlpha(0.7);
// Button down events
this.leftButton.on('pointerdown', () => {
this.isMovingLeft = true;
});
this.rightButton.on('pointerdown', () => {
this.isMovingRight = true;
});
// Button up events (stop movement when button is released)
this.leftButton.on('pointerup', () => {
this.isMovingLeft = false;
});
this.rightButton.on('pointerup', () => {
this.isMovingRight = false;
});
// Track if ghost is awake
this.isAwake = true; // Assuming ghost is already awake when outside
this.isMovingLeft = false;
this.isMovingRight = false;
}
update() {
// Enable movement
if (this.isAwake) {
// Check keyboard input
if ((this.cursors.left.isDown || this.isMovingLeft) && this.ghost.x > 0) {
this.ghost.x -= 2; // Move left
} else if ((this.cursors.right.isDown || this.isMovingRight) && this.ghost.x < config.width) {
this.ghost.x += 2; // Move right
}
// Add any outdoor-specific interactions here
// For example, opening a window, interacting with objects, etc.
}
}
returnInside() {
// Prepare ghost state to pass back
const updatedGhostState = {
x: this.ghost.x,
y: this.ghost.y,
angle: this.ghost.angle,
scale: this.ghost.scale,
weaponPicked: this.ghostState.weaponPicked,
texture: this.ghostState.texture
};
// Switch back to InGhostHouseScene, passing the updated state
this.scene.start('InGhostHouseScene', { ghostState: updatedGhostState });
}
}
Explanation of the OutGhostHouseScene:
-
Initialization (init method):
- Receives the ghost's state from the previous scene to maintain continuity.
- If no state is passed, it initializes default values.
-
Creation (create method):
- Sets up the outside background.
- Places the ghost based on the received state.
- Manages the weapon's visibility based on whether it's picked up.
- Adds a "Return Inside" button to go back to the
InGhostHouseScene.
- Sets up movement controls similar to
InGhostHouseScene.
-
Update (update method):
- Allows the ghost to move left or right if awake.
-
Returning Inside (returnInside method):
- Captures the current state of the ghost.
- Transitions back to
InGhostHouseScene, passing the updated state.
3. Handle State Management
To maintain the ghost's state between scenes, we'll utilize Phaser's scene data passing mechanism. This involves passing data when starting a scene and retrieving it in the new scene's init method.
Update InGhostHouseScene to Handle Incoming Data:
Modify the InGhostHouseScene to accept incoming ghost state data when transitioning back from OutGhostHouseScene.
// In InGhostHouseScene class
init(data) {
// Receive ghost state from the previous scene
this.ghostState = data.ghostState || {
x: 260,
y: 340,
angle: 0,
scale: 0.25,
weaponPicked: false,
texture: 'ghost'
};
}
create() {
// Add main menu background image
this.add.image(320, 240, 'mainMenu').setDisplaySize(640, 480); // Centered
// Create a drop shadow for the play button
const shadow = this.add.graphics();
shadow.fillStyle(0x000000, 0.5); // Black color with some transparency
shadow.fillEllipse(320, 430, 200, 60); // Draw shadow ellipse (x, y, width, height)
// Add play button
const playButton = this.add.image(320, 390, 'playButton').setInteractive();
// Scale play button to make it much smaller
playButton.setScale(0.25); // Adjust the scale for a smaller button
// Add click listener to play button
playButton.on('pointerdown', () => {
console.log('Play button clicked!');
this.scene.start('InGhostHouseScene', { ghostState: this.ghostState }); // Pass ghost state
});
// Add background music
this.bgMusic = this.sound.add('bgMusic', { loop: true, volume: 0.5 });
this.bgMusic.play();
}
// Ensure to update ghostState when scene transitions
wakeUpGhost() {
if (!this.isAwake) {
// Move ghost to bottom of screen (floor level)
this.ghost.x = 260; // Center horizontally
this.ghost.y = 340; // Bottom near floor
this.ghost.angle = 0; // Set upright position
this.ghost.setScale(0.25);
this.isAwake = true; // Mark ghost as awake
this.wakeUpButton.setVisible(false); // Hide wake-up button
// Update ghostState
this.ghostState = {
x: this.ghost.x,
y: this.ghost.y,
angle: this.ghost.angle,
scale: this.ghost.scale,
weaponPicked: this.weaponPicked,
texture: this.ghost.texture.key
};
}
}
// Similarly, update ghostState in other interactions
// For example, in putGhostToSleep(), pickWeapon(), dropWeapon(), etc.
Explanation:
-
init Method:
- Receives
ghostState when the scene is started from another scene (e.g., OutGhostHouseScene).
- If no
ghostState is passed, initializes default values.
-
create Method:
- When transitioning to
InGhostHouseScene from MainMenuScene, it passes the current ghostState.
-
Updating ghostState:
- After each interaction that modifies the ghost's state (like moving, picking up a weapon), update the
ghostState object accordingly.
- This ensures that when transitioning to another scene, the current state is preserved and passed along.
Ensure all methods in InGhostHouseScene that modify the ghost's state also update the ghostState object.
4. Update Scene Transition Logic
Modify the openDoor method in InGhostHouseScene to transition to the OutGhostHouseScene, passing the current ghost state.
// In InGhostHouseScene class
openDoor() {
// Prepare ghost state to pass to the next scene
const updatedGhostState = {
x: this.ghost.x,
y: this.ghost.y,
angle: this.ghost.angle,
scale: this.ghost.scale,
weaponPicked: this.weaponPicked,
texture: this.ghost.texture.key
};
// Switch to `OutGhostHouseScene`, passing the ghost state
this.scene.start('OutGhostHouseScene', { ghostState: updatedGhostState });
}
Explanation:
openDoor Method:
- Gathers the current state of the ghost.
- Starts the
OutGhostHouseScene, passing the ghostState as data.
5. Update Phaser Configuration
Add the new OutGhostHouseScene to the Phaser game configuration to ensure it's recognized and can be transitioned to.
// Configuration for the Phaser game
const config = {
type: Phaser.AUTO,
width: 640,
height: 480,
parent: 'game-container',
scene: [PreloadScene, MainMenuScene, InGhostHouseScene, OutGhostHouseScene], // Added OutGhostHouseScene
audio: {
disableWebAudio: false
}
};
// Initialize Phaser game
const game = new Phaser.Game(config);
Note: Ensure that the OutGhostHouseScene is included in the scene array.
6. Complete Code Integration
Here's how the complete updated code would look with the new OutGhostHouseScene integrated. For clarity, only the modified sections are included, assuming other parts of your original code remain unchanged.
// Preload Scene: Loads all assets and shows loading bar
class PreloadScene extends Phaser.Scene {
constructor() {
super({ key: 'PreloadScene' });
}
preload() {
// ... existing preload code ...
// Load new assets for OutGhostHouseScene
this.load.image('ghostHouseOutside', 'assets/images/ghost-house-outside.png');
}
create() {
// Start Main Menu Scene after loading
this.scene.start('MainMenuScene');
}
}
// Main Menu Scene: Displays main menu with play button and background music
class MainMenuScene extends Phaser.Scene {
constructor() {
super({ key: 'MainMenuScene' });
}
create() {
// ... existing create code ...
}
// ... existing shutdown method ...
}
// In Ghost House Scene: Shows the ghost's house and allows user interaction with the ghost
class InGhostHouseScene extends Phaser.Scene {
constructor() {
super({ key: 'InGhostHouseScene' });
}
init(data) {
// Receive ghost state from the previous scene
this.ghostState = data.ghostState || {
x: 260,
y: 340,
angle: 0,
scale: 0.25,
weaponPicked: false,
texture: 'ghost'
};
}
create() {
// ... existing create code, modified to use this.ghostState ...
// Example of setting ghost's initial state based on ghostState
this.ghost = this.add.image(this.ghostState.x, this.ghostState.y, this.ghostState.texture)
.setOrigin(0.5, 0.5)
.setScale(this.ghostState.scale)
.setAngle(this.ghostState.angle);
// Handle weapon visibility
if (this.ghostState.weaponPicked) {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85)
.setVisible(false);
} else {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85);
}
// ... rest of the create method ...
}
update() {
// ... existing update code, updating this.ghostState accordingly ...
}
// ... existing methods (wakeUpGhost, putGhostToSleep, pickWeapon, dropWeapon) with ghostState updates ...
openDoor() {
// Prepare ghost state to pass to the next scene
const updatedGhostState = {
x: this.ghost.x,
y: this.ghost.y,
angle: this.ghost.angle,
scale: this.ghost.scale,
weaponPicked: this.weaponPicked,
texture: this.ghost.texture.key
};
// Switch to `OutGhostHouseScene`, passing the ghost state
this.scene.start('OutGhostHouseScene', { ghostState: updatedGhostState });
}
}
// Out Ghost House Scene: Shows the outside of the ghost house and allows user interaction with the ghost
class OutGhostHouseScene extends Phaser.Scene {
constructor() {
super({ key: 'OutGhostHouseScene' });
}
init(data) {
// Receive ghost state from the previous scene
this.ghostState = data.ghostState || {
x: 260,
y: 340,
angle: 0,
scale: 0.25,
weaponPicked: false,
texture: 'ghost'
};
}
create() {
// Add background image for outside
this.add.image(320, 240, 'ghostHouseOutside').setDisplaySize(640, 480);
// Add ghost based on the received state
this.ghost = this.add.image(this.ghostState.x, this.ghostState.y, this.ghostState.texture)
.setOrigin(0.5, 0.5)
.setScale(this.ghostState.scale)
.setAngle(this.ghostState.angle);
// Handle weapon visibility
if (this.ghostState.weaponPicked) {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85)
.setVisible(false);
} else {
this.weapon = this.add.image(350, 325, 'weapon')
.setOrigin(0.5, 0.5)
.setScale(0.2)
.setAngle(85);
}
// Add interaction buttons
this.returnButton = this.add.text(320, 450, 'Return Inside', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.on('pointerdown', () => this.returnInside());
// Keyboard controls for movement
this.cursors = this.input.keyboard.createCursorKeys();
// Left and Right buttons for touch input
this.leftButton = this.add.image(100, 400, 'leftButton').setInteractive();
this.rightButton = this.add.image(540, 400, 'rightButton').setInteractive();
// Scale and transparency for the buttons
this.leftButton.setScale(0.5).setAlpha(0.7);
this.rightButton.setScale(0.5).setAlpha(0.7);
// Button down events
this.leftButton.on('pointerdown', () => {
this.isMovingLeft = true;
});
this.rightButton.on('pointerdown', () => {
this.isMovingRight = true;
});
// Button up events (stop movement when button is released)
this.leftButton.on('pointerup', () => {
this.isMovingLeft = false;
});
this.rightButton.on('pointerup', () => {
this.isMovingRight = false;
});
// Track if ghost is awake
this.isAwake = true; // Assuming ghost is already awake when outside
this.isMovingLeft = false;
this.isMovingRight = false;
}
update() {
// Enable movement
if (this.isAwake) {
// Check keyboard input
if ((this.cursors.left.isDown || this.isMovingLeft) && this.ghost.x > 0) {
this.ghost.x -= 2; // Move left
} else if ((this.cursors.right.isDown || this.isMovingRight) && this.ghost.x < config.width) {
this.ghost.x += 2; // Move right
}
// Add any outdoor-specific interactions here
}
}
returnInside() {
// Prepare ghost state to pass back
const updatedGhostState = {
x: this.ghost.x,
y: this.ghost.y,
angle: this.ghost.angle,
scale: this.ghost.scale,
weaponPicked: this.ghostState.weaponPicked,
texture: this.ghostState.texture
};
// Switch back to InGhostHouseScene, passing the updated state
this.scene.start('InGhostHouseScene', { ghostState: updatedGhostState });
}
}
// Configuration for the Phaser game
const config = {
type: Phaser.AUTO,
width: 640,
height: 480,
parent: 'game-container',
scene: [PreloadScene, MainMenuScene, InGhostHouseScene, OutGhostHouseScene], // Added OutGhostHouseScene
audio: {
disableWebAudio: false
}
};
// Initialize Phaser game
const game = new Phaser.Game(config);
window.addEventListener('resize', () => {
const canvas = document.querySelector('canvas');
if (canvas) {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const scale = Math.min(windowWidth / 640, windowHeight / 480);
canvas.style.transform = `scale(${scale})`;
canvas.style.transformOrigin = 'top left';
}
});
Key Points in the Complete Integration:
-
Asset Loading:
- The
ghostHouseOutside image is loaded in the PreloadScene.
-
State Management:
- Both
InGhostHouseScene and OutGhostHouseScene have an init method to receive the ghostState.
- When transitioning between scenes, the current state of the ghost is passed along to maintain consistency.
-
Scene Transitions:
InGhostHouseScene transitions to OutGhostHouseScene via the openDoor method, passing the current ghostState.
OutGhostHouseScene can return to InGhostHouseScene via the returnInside method, passing back the updated ghostState.
-
Ghost Representation:
- The ghost's texture, position, angle, and scale are all maintained based on the
ghostState.
- The weapon's visibility is managed based on whether it's picked up or not.
-
User Interaction:
- Both scenes allow the user to move the ghost left and right using keyboard arrows or on-screen buttons.
- Additional interactions specific to each scene can be implemented as needed.
7. Additional Considerations
By following the above implementation, you've successfully added a new OutGhostHouseScene to your Phaser game, enabling smooth transitions between the inside and outside of the ghost house while maintaining the ghost's state across scenes.