Hi, I have 2 JS script, gamescene.js and hudscene.js. How do I call the zoomIn() function in gamescene.js from hudscene.js?
Gamescene.js
export class GameScene extends Phaser.Scene {
constructor() {
super({
key: SCENE_KEYS.GAME_SCENE
});
}
create() {
function zoomIn() {
var currentZoom = dataManager.store.get(
DATA_MANAGER_STORE_KEYS.OPTIONS_ZOOMSTATE
);
currentZoom - 0.07;
if (currentZoom <= 0.65) {
currentZoom = 0.65;
}
gameCamera.zoom = currentZoom;
}
}
}
hudscene.js
export class HUDScene extends Phaser.Scene {
constructor() {
super({
key: SCENE_KEYS.HUD_SCENE
});
}
create() {
const zoomButton = this.add.image(933, 7, 'ZOOMBUTTON').setOrigin(0).setInteractive();
zoomButton.on('pointerdown', () => {
// invoke zoomIn() from Gamescene.js
});
}
}
samme
July 3, 2024, 3:06pm
2
this.scene.get(SCENE_KEYS.GAME_SCENE).zoomIn();
Thanks for replying! I am getting an error “Property ‘zoomIn’ does not exist on type ‘Scene’.” for some reason?
export class GameScene extends Phaser.Scene {
constructor() {
super({
key: SCENE_KEYS.GAME_SCENE
});
}
create() {
}
zoomIn() {
var currentZoom = dataManager.store.get(DATA_MANAGER_STORE_KEYS.OPTIONS_ZOOMSTATE);
currentZoom - 0.07;
if (currentZoom <= 0.65) {
currentZoom = 0.65;
}
gameCamera.zoom = currentZoom;
}
}
You need to change the zoomIn function declaration location so that it becomes a method of the scene class.
I have tried that but the error is still persisting.
samme
July 3, 2024, 3:57pm
6
This is correct. get()
can return any Scene
, but only GameScene
has zoomIn()
.
You can add a type guard
const gameScene = this.scene.get(SCENE_KEYS.GAME_SCENE);
if (!(gameScene instanceof GameScene)) {
throw new Error('GameScene not found');
}
gameScene.zoomIn();
or a type assertion.
const gameScene = this.scene.get(SCENE_KEYS.GAME_SCENE);
// YOLO
(gameScene as GameScene).zoomIn();
I have tried both solutions but they throw up the error “Type assertion expressions can only be used in TypeScript files.” So I decided to use EventEmitter instead which gave me no errors. Thx a lot!
gamescene.js
import eventsManager from ‘…/common/eventsmanager.js’;
export class GameScene extends Phaser.Scene {
constructor() {
super({
key: SCENE_KEYS.GAME_SCENE
});
}
create() {
eventsManager.on(‘zoom-in’, zoomIn, this);
function zoomIn() {
var currentZoom = dataManager.store.get(
DATA_MANAGER_STORE_KEYS.OPTIONS_ZOOMSTATE
);
currentZoom -= 0.07;
if (currentZoom <= 0.65) {
currentZoom = 0.65;
}
gameCamera.zoom = currentZoom;
}
}
}
eventsmanager.js
import Phaser from ‘…/lib/phaser.js’;
const eventsManager = new Phaser.Events.EventEmitter()
export default eventsManager
hudscene.js
import eventsManager from ‘…/common/eventsmanager.js’;
export class HUDScene extends Phaser.Scene {
constructor() {
super({
key: SCENE_KEYS.HUD_SCENE
});
}
create() {
const zoomButton = this.add.image(933, 7, ‘ZOOMBUTTON’).setOrigin(0).setInteractive();
zoomButton.on(‘pointerdown’, () => {
eventsManager.emit(‘zoom-in’);
});
}
}