To implement the OutGhostHouseScene and ensure that the ghost's state (such as position, texture, and whether the weapon is picked up) is preserved across scenes, we'll introduce a global gameState object. This object will store the necessary properties of the ghost and can be accessed and modified by all scenes.
Below is the updated code with the following additions and modifications:
- Global
gameState Object: This object holds the ghost's state and is defined at the top to be accessible by all scenes.
OutGhostHouseScene Class: This new scene mirrors the InGhostHouseScene but uses the exterior background and includes a button to return to the interior scene.
- Modifications to
InGhostHouseScene: Adjusted to utilize the gameState for initializing and updating the ghost's state.
- Phaser Game Configuration Update: Added
OutGhostHouseScene to the list of scenes in the game configuration.
Here is the complete updated code:
// Define global gameState for sharing ghost's state between scenes
const gameState = {
ghostX: 250, // initial position in bed
ghostY: 300,
ghostAngle: -90,
ghostScale: 0.2,
isAwake: false,
weaponPicked: false,
ghostTexture: 'ghost'
};
// Preload Scene: Loads all assets and shows loading bar
class PreloadScene extends Phaser.Scene {
constructor() {
super({ key: 'PreloadScene' });
}
preload() {
// Add loading bar background
const loadingBarBg = this.add.graphics();
loadingBarBg.fillStyle(0x222222, 1);
loadingBarBg.fillRect(200, 220, 240, 50);
// Add loading bar
const loadingBar = this.add.graphics();
// Display loading text
const loadingText = this.add.text(320, 200, 'Loading...', { fontSize: '20px', fill: '#ffffff' });
loadingText.setOrigin(0.5, 0.5);
// Update loading bar as assets are loaded
this.load.on('progress', (value) => {
loadingBar.clear();
loadingBar.fillStyle(0xffffff, 1);
loadingBar.fillRect(200, 220, 240 * value, 50);
});
// Remove loading bar once complete
this.load.on('complete', () => {
loadingBar.destroy();
loadingBarBg.destroy();
loadingText.destroy();
});
const leftButtonDataURI = 'data:image/svg+xml;base64,' + btoa(`
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
<rect x="5" y="5" width="90" height="90" fill="#333333" stroke="#ffffff" stroke-width="5"/>
<polygon points="60,30 40,50 60,70" fill="#ffffff"/>
</svg>
`);
const rightButtonDataURI = 'data:image/svg+xml;base64,' + btoa(`
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
<rect x="5" y="5" width="90" height="90" fill="#333333" stroke="#ffffff" stroke-width="5"/>
<polygon points="40,30 60,50 40,70" fill="#ffffff"/>
</svg>
`);
// Load assets
this.load.image('mainMenu', 'assets/images/main-menu.png');
this.load.image('playButton', 'assets/images/play-button.png');
this.load.image('ghostHouse', 'assets/images/ghost-house.jpg');
this.load.image('ghostHouseOutside', 'assets/images/ghost-house-outside.jpg');
this.load.image('ghost', 'assets/images/ghost.webp');
this.load.image('the-ghost', 'assets/images/the-ghost.png');
this.load.image('weapon', 'assets/images/weapon.png');
this.load.audio('bgMusic', ['assets/audio/background-music.wav']);
this.load.image('leftButton', leftButtonDataURI);
this.load.image('rightButton', rightButtonDataURI);
}
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() {
// 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'); // Start In Ghost House Scene on button click
});
// Add background music
this.bgMusic = this.sound.add('bgMusic', { loop: true, volume: 0.5 });
this.bgMusic.play();
}
// Optional: Stop music when scene is shutdown
shutdown() {
if (this.bgMusic) {
this.bgMusic.stop();
}
}
}
// 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' });
}
create() {
// Add ghost house background image
this.add.image(320, 240, 'ghostHouse').setDisplaySize(640, 480);
// Add weapon
this.weapon = this.add.image(350, 325, 'weapon').setOrigin(0.5, 0.5);
this.weapon.setScale(0.2);
this.weapon.angle = 85;
this.weaponPicked = gameState.weaponPicked;
// Ghost character setup
this.ghost = this.add.image(gameState.ghostX, gameState.ghostY, gameState.ghostTexture).setOrigin(0.5, 0.5);
this.ghost.setScale(gameState.ghostScale);
this.ghost.angle = gameState.ghostAngle;
// Wake-up button setup
this.wakeUpButton = this.add.text(320, 450, 'Wake Up', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.on('pointerdown', () => this.wakeUpGhost());
// "Go Back to Sleep" button setup (initially hidden)
this.sleepButton = this.add.text(320, 450, 'Go Back to Sleep', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(false)
.on('pointerdown', () => this.putGhostToSleep());
// "Pick Weapon" / "Drop Weapon" button setup
this.pickWeaponButton = this.add.text(320, 450, 'Pick Weapon', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(!this.weaponPicked)
.on('pointerdown', () => this.pickWeapon());
this.dropWeaponButton = this.add.text(320, 450, 'Drop Weapon', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(this.weaponPicked)
.on('pointerdown', () => this.dropWeapon());
// "Open Door" button setup
this.openDoorButton = this.add.text(320, 450, 'Open Door', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(false)
.on('pointerdown', () => this.openDoor());
// 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 = gameState.isAwake;
this.isMovingLeft = false;
this.isMovingRight = false;
}
update() {
// If the ghost is awake, 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 < this.sys.game.config.width) {
this.ghost.x += 2; // Move right
}
// Update gameState with ghost's current position
gameState.ghostX = this.ghost.x;
gameState.ghostY = this.ghost.y;
// Check if the ghost is near the bed position to show the sleep button
if (this.ghost.x > 170 && this.ghost.x < 270) {
this.sleepButton.setVisible(true);
} else {
this.sleepButton.setVisible(false);
}
if (!this.weaponPicked) {
// Check if the ghost is near the weapon table position to show the pick weapon button
if (this.ghost.x > 300 && this.ghost.x < 400) {
this.pickWeaponButton.setVisible(true);
} else {
this.pickWeaponButton.setVisible(false);
}
} else {
// Check if the ghost is near the weapon table position to show the drop weapon button
if (this.ghost.x > 300 && this.ghost.x < 400) {
this.dropWeaponButton.setVisible(true);
} else {
this.dropWeaponButton.setVisible(false);
}
}
// Check if the ghost is near the door position to show the open door button
if (this.ghost.x > 430 && this.ghost.x < 530) {
this.openDoorButton.setVisible(true);
} else {
this.openDoorButton.setVisible(false);
}
}
}
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
// Update gameState
gameState.isAwake = true;
gameState.ghostX = this.ghost.x;
gameState.ghostY = this.ghost.y;
gameState.ghostAngle = this.ghost.angle;
gameState.ghostScale = this.ghost.scaleX; // Assuming uniform scale based on X
this.wakeUpButton.setVisible(false); // Hide wake-up button
this.sleepButton.setVisible(false);
this.pickWeaponButton.setVisible(!this.weaponPicked);
this.dropWeaponButton.setVisible(this.weaponPicked);
this.openDoorButton.setVisible(false);
}
}
putGhostToSleep() {
if (this.isAwake) {
// Reset ghost position to bed and put it to sleep
this.ghost.x = 250; // Bed's x position
this.ghost.y = 300; // Bed's y position
this.ghost.angle = -90; // Lie down position
this.ghost.setScale(0.2); // Original size
this.isAwake = false; // Mark ghost as asleep
// Update gameState
gameState.isAwake = false;
gameState.ghostX = this.ghost.x;
gameState.ghostY = this.ghost.y;
gameState.ghostAngle = this.ghost.angle;
gameState.ghostScale = this.ghost.scaleX; // Assuming uniform scale based on X
this.wakeUpButton.setVisible(true); // Show wake-up button again
this.sleepButton.setVisible(false); // Hide sleep button
// Reset ghost texture and weapon if weapon was picked up
if (this.weaponPicked) {
this.ghost.setTexture('ghost'); // Change back to original ghost texture
this.weapon.setVisible(true); // Make weapon visible again
this.weaponPicked = false; // Reset weapon picked state
gameState.weaponPicked = false; // Update gameState
this.pickWeaponButton.setVisible(true);
this.dropWeaponButton.setVisible(false);
}
}
}
pickWeapon() {
// Check if the weapon is already picked up
if (this.weaponPicked) return;
// Change ghost's image to "the-ghost"
this.ghost.setTexture('the-ghost');
// Hide weapon and pickWeaponButton permanently after picking up
this.weapon.setVisible(false);
this.pickWeaponButton.setVisible(false);
this.dropWeaponButton.setVisible(true);
// Set weapon picked state to true
this.weaponPicked = true;
gameState.weaponPicked = true; // Update gameState
}
dropWeapon() {
// Check if the weapon is already picked up
if (!this.weaponPicked) return;
// Change ghost's image back to "ghost"
this.ghost.setTexture('ghost');
// Show weapon and pickWeaponButton, hide dropWeaponButton
this.weapon.setVisible(true);
this.pickWeaponButton.setVisible(true);
this.dropWeaponButton.setVisible(false);
// Set weapon picked state to false
this.weaponPicked = false;
gameState.weaponPicked = false; // Update gameState
}
openDoor() {
// Switch to `OutGhostHouseScene`
this.scene.start('OutGhostHouseScene');
}
}
// Out Ghost House Scene: Shows the exterior of the ghost house and allows interaction with the ghost
class OutGhostHouseScene extends Phaser.Scene {
constructor() {
super({ key: 'OutGhostHouseScene' });
}
create() {
// Add ghost house exterior background image
this.add.image(320, 240, 'ghostHouseOutside').setDisplaySize(640, 480);
// Add weapon if it's placed outside
if (gameState.weaponPicked) {
this.weapon = this.add.image(350, 325, 'weapon').setOrigin(0.5, 0.5);
this.weapon.setScale(0.2);
this.weapon.angle = 85;
this.weapon.setVisible(false); // Weapon is carried by the ghost
} else {
this.weapon = this.add.image(350, 325, 'weapon').setOrigin(0.5, 0.5);
this.weapon.setScale(0.2);
this.weapon.angle = 85;
this.weaponPicked = false;
this.weapon.setVisible(true);
}
// Ghost character setup
this.ghost = this.add.image(gameState.ghostX, gameState.ghostY, gameState.ghostTexture).setOrigin(0.5, 0.5);
this.ghost.setScale(gameState.ghostScale);
this.ghost.angle = gameState.ghostAngle;
// "Go Back" button setup
this.goBackButton = this.add.text(320, 450, 'Enter House', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.on('pointerdown', () => this.enterHouse());
// Wake-up button setup (visible only if ghost is asleep)
this.wakeUpButton = this.add.text(320, 450, 'Wake Up', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(!gameState.isAwake)
.on('pointerdown', () => this.wakeUpGhost());
// "Pick Weapon" / "Drop Weapon" button setup
this.pickWeaponButton = this.add.text(320, 450, 'Pick Weapon', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(!this.weaponPicked)
.on('pointerdown', () => this.pickWeapon());
this.dropWeaponButton = this.add.text(320, 450, 'Drop Weapon', { fontSize: '20px', fill: '#ffffff' })
.setOrigin(0.5)
.setInteractive()
.setVisible(this.weaponPicked)
.on('pointerdown', () => this.dropWeapon());
// 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 = gameState.isAwake;
this.isMovingLeft = false;
this.isMovingRight = false;
}
update() {
// If the ghost is awake, 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 < this.sys.game.config.width) {
this.ghost.x += 2; // Move right
}
// Update gameState with ghost's current position
gameState.ghostX = this.ghost.x;
gameState.ghostY = this.ghost.y;
// If weapon was dropped outside, show the drop weapon button when near the weapon
if (!this.weaponPicked) {
if (Phaser.Math.Distance.Between(this.ghost.x, this.ghost.y, this.weapon.x, this.weapon.y) < 50) {
this.pickWeaponButton.setVisible(true);
} else {
this.pickWeaponButton.setVisible(false);
}
} else {
// If weapon is picked, show drop weapon button when near the house entrance
if (this.ghost.x > 430 && this.ghost.x < 530) { // Assuming door position
this.dropWeaponButton.setVisible(true);
} else {
this.dropWeaponButton.setVisible(false);
}
}
}
}
wakeUpGhost() {
if (!this.isAwake) {
// Move ghost to a default position outside
this.ghost.x = 260; // Example position
this.ghost.y = 340;
this.ghost.angle = 0; // Set upright position
this.ghost.setScale(0.25);
this.isAwake = true; // Mark ghost as awake
// Update gameState
gameState.isAwake = true;
gameState.ghostX = this.ghost.x;
gameState.ghostY = this.ghost.y;
gameState.ghostAngle = this.ghost.angle;
gameState.ghostScale = this.ghost.scaleX; // Assuming uniform scale based on X
this.wakeUpButton.setVisible(false); // Hide wake-up button
this.goBackButton.setVisible(false);
this.pickWeaponButton.setVisible(!this.weaponPicked);
this.dropWeaponButton.setVisible(this.weaponPicked);
}
}
pickWeapon() {
// Check if the weapon is already picked up
if (this.weaponPicked) return;
// Change ghost's image to "the-ghost"
this.ghost.setTexture('the-ghost');
// Hide weapon and pickWeaponButton permanently after picking up
this.weapon.setVisible(false);
this.pickWeaponButton.setVisible(false);
this.dropWeaponButton.setVisible(true);
// Set weapon picked state to true
this.weaponPicked = true;
gameState.weaponPicked = true; // Update gameState
}
dropWeapon() {
// Check if the weapon is already picked up
if (!this.weaponPicked) return;
// Change ghost's image back to "ghost"
this.ghost.setTexture('ghost');
// Show weapon and pickWeaponButton, hide dropWeaponButton
this.weapon.setVisible(true);
this.pickWeaponButton.setVisible(true);
this.dropWeaponButton.setVisible(false);
// Set weapon picked state to false
this.weaponPicked = false;
gameState.weaponPicked = false; // Update gameState
}
enterHouse() {
// Switch back to `InGhostHouseScene`
this.scene.start('InGhostHouseScene');
}
}
// Configuration for the Phaser game
const config = {
type: Phaser.AUTO,
width: 640,
height: 480,
parent: 'game-container',
scene: [PreloadScene, MainMenuScene, InGhostHouseScene, 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';
}
});
Explanation of the Additions and Modifications
-
Global gameState Object:
const gameState = {
ghostX: 250, // initial position in bed
ghostY: 300,
ghostAngle: -90,
ghostScale: 0.2,
isAwake: false,
weaponPicked: false,
ghostTexture: 'ghost'
};
- This object holds the essential properties of the ghost, allowing both
InGhostHouseScene and OutGhostHouseScene to access and modify the ghost's state consistently.
-
OutGhostHouseScene Class:
- Mirrors the structure of
InGhostHouseScene but uses the exterior background image (ghostHouseOutside.jpg).
- Initializes the ghost's position, angle, scale, and texture based on
gameState.
- Includes buttons for picking/dropping the weapon and entering the house.
- Updates the
gameState as the ghost moves or interacts with objects.
-
Modifications to InGhostHouseScene:
- Adjusted the
create method to initialize the ghost's properties from gameState.
- In the
update method, updates the gameState with the ghost's current position.
- When waking up or sleeping the ghost, updates the relevant properties in
gameState.
- Modified the
openDoor method to start the OutGhostHouseScene.
-
Phaser Game Configuration Update:
scene: [PreloadScene, MainMenuScene, InGhostHouseScene, OutGhostHouseScene],
- Added
OutGhostHouseScene to the list of scenes so that Phaser is aware of it and can transition to it when needed.
-
Weapon Handling in OutGhostHouseScene:
- If the weapon is picked up (
gameState.weaponPicked === true), the weapon image is hidden as the ghost carries it.
- If the weapon is dropped, it becomes visible in the exterior scene.
-
Returning to InGhostHouseScene:
- The
OutGhostHouseScene includes an "Enter House" button (goBackButton) that allows the player to return to the interior scene, maintaining the ghost's current state.
Additional Recommendations
With these additions and modifications, your game will have a functional OutGhostHouseScene that maintains the ghost's state consistently across scenes, providing a seamless user experience.