Utilizing the camera from one Phaser scene in a different scene

I have a camera setup using Bootstrap

import Phaser from 'phaser'

export default class Bootstrap extends Phaser.Scene {
  private camera: Phaser.Cameras.Scene2D.Camera | null = null
  private zoomLevel: number = 1
  constructor() {
    super('Bootstrap')
  }

  private resizeCamera() {
    // Responsively set camera size to window size
    const width = window.innerWidth;
    const height = window.innerHeight;
    
    this.zoomLevel = (width > 600) ? 1.5 : 1;

    this.cameras.main.zoom = this.zoomLevel
    this.cameras.main.setSize(width, height);
    this.cameras.main.setScroll(0, 0);
  }

  create() {
    this.camera = this.cameras.main;

    this.resizeCamera();
    this.scale.on('resize', this.resizeCamera, this)
    
    // launch GameScene and pass in the camera
    this.scene.launch('GameScene', { 
      existingCamera: this.camera,
    });
  }
}

I am using this.scene.launch to run GameScene alongside Bootstrap

I'm trying to utilize the camera from Bootstrap in GameScene

import Phaser from 'phaser'

export default class GameScene extends Phaser.Scene {
  private player: Phaser.Physics.Arcade.Sprite | null = null;
  private camera: Phaser.Cameras.Scene2D.Camera | null = null
  constructor() {
    super('GameScene')
  }

  init(data: any) {
    this.camera = data.existingCamera;
  }

  create() {
    // Create player sprite and add physics
    this.player = this.physics.add.sprite(1200, 1200, 'adam', 18)

    this.camera?.setBounds(0, 0, 2400, 2400);
    this.camera?.startFollow(this.player, true);
  }
}

I use the init function to access the camera from Bootstrap and apply it in GameScene. When I console.log the this.camera in my create function, I see that the scene parent is Bootstrap, but my camera isn't following the player. What am I missing?

Additionally, is it advisable to create a global camera for multiple scenes or should each scene have its own camera, even if they share functionalities?

Answer №1

Sharing a camera is generally not recommended due to potential side effects that may arise.

If you do wish to share settings, one approach could be utilizing inheritance.

You can create a custom scene tailored to your camera requirements. In scenes where these settings are needed, inherit from the custom Scene. For other scenes, simply inherit from the base Phaser.Scene.

Consider this example implementation:

class MyCameraScene extends Phaser.Scene {
    constructor(name){
        super(name);
    }

    init(){
        this.resizeCamera();
        this.scale.on('resize', this.resizeCamera, this)
    }

    resizeCamera() {
        // Adjust camera size responsively based on window dimensions
        const width = window.innerWidth;
        const height = window.innerHeight;
        
        this.zoomLevel = (width > 600) ? 1.5 : 1;
    
        this.cameras.main.zoom = this.zoomLevel
        this.cameras.main.setSize(width, height);
        this.cameras.main.setScroll(0, 0);
    }
}

class Bootstrap extends MyCameraScene {
    // ...
}

class GameScene extends MyCameraScene { 
    // ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the class of the appropriate navigation tab when the corresponding div is scrolled into view

After reading similar questions and doing some research on scrollspy, I don't think it will provide the functionality I need. It seems to only support bootstrap style highlighting. If there is more to it that I'm not aware of, please inform me! ...

Utilize jQuery to seamlessly transfer each recorded audio file from rows to corresponding input fields within the table

I have a table below with 2 rows but it can be doubled with a button (Add another Word media) and only one submit button for all rows: <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class=&quo ...

`The challenge of navigating within Material UI tabs in a React js project`

In my current project, I am utilizing React Js along with the Material UI Tabs component to switch between two different components. However, I have encountered an issue where when I navigate to Tab 2 or Tab 1 by clicking on them, the route changes and th ...

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

execute a function for every regex match found within a string

When working with WordPress or PHP in general, I came across this interesting recommendation for email obfuscation, and I would like to: Convert email addresses to mailto links Encode the mailto links using str_13() Decode them client-side using JavaScri ...

Utilize Javascript to extract information from an array of XML objects

I have an XML object that I need to parse in order to extract startdate and end date data. My goal is to compare and group appointments with the same date together, but I don't have much experience manipulating XML - I'm more comfortable with JSO ...

Typedoc encountering an issue due to the require syntax

I am currently attempting to create documentation using typedoc. The lines in my typescript file are as follows: var validator: any = require('validator'); import * as _ from 'lodash'; var mqtt: any = require('mqtt'); var fs ...

Combining multiple responses to create a single JSON file

Is there a way to consolidate multiple responses into a single JSON object? Much appreciated! Upon running the code, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client .... var trackArra ...

Determining whether a question is finished or unfinished can be based on the page index

Trying to create a progress bar for a form with 11 questions. Each question has an array of objects that flag whether it's complete or incomplete based on user interactions. The aim is for the progress to update when users click 'next' or &a ...

The organizational structure of data in MongoDB for posts, comments, saved content, and likes

I am currently diving into the world of MEANJS web development and working on structuring my data. As a newcomer to the NoSql concept, I am seeking guidance on the best practices to follow. The data I need to store includes: questions answers likes saved ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

The submit function in Jquery is not functioning properly within the success callback of an Ajax request

After successfully submitting a form in AJAX using POST, I receive a new form that needs to be automatically submitted in jQuery. However, for some reason, the .submit() function seems to be ignored and I can't figure out why. I've tried adding ...

The performance of Ionic scroll is hindered by a slow response time coupled with a

I'm experiencing an issue where the page loads square by square when I scroll, which looks like this: https://i.sstatic.net/yHNLx.jpg Here is the code snippet: categoryList.html <ion-header-bar align-title="center" class="bar-stable"> < ...

The ajaxForm function is failing to execute properly and is not providing any error messages

When trying to use jQuery ajaxForm, I encounter a strange issue. I am attempting to set up a form for file upload with progress percentage tracking. However, my ajaxForm function does not seem to be triggering at all. Below is the code snippet I am usin ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

Is there a way in Python to translate JavascriptSerializer into a datetime object?

My JSON file contains date and time in the format generated by JavascriptSerializer, shown below: {"StartDate": "/Date(1519171200000)/", "EndDate": "/Date(1519257600000)/",} How can I convert it to datetime formats like these? "2012-04-23T18:25:43.511Z" ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

Updating a Tag's Class with the use of getElementsByTagName

I need assistance changing the class of all elements with the 'input' tag using the getElementsByTagName method. I am struggling to successfully modify their classes as my attempts so far have not been fruitful. Any guidance would be greatly appr ...

Could the quantity of JavaScript files impact the performance of a project and cause any delays?

In my current HTML and JavaScript project, I am incorporating multiple JavaScript files. I'm curious to learn about the potential impact of having numerous JavaScript files on a web project's efficiency and speed. Can anyone shed some light on th ...