Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve:

create()
    {
       const map = this.make.tilemap({ key: 'mainmap' })
       const tileset = map.addTilesetImage('Serene_Village_16x16', 'tiles', 16, 16, 1, 2)

       const Next1 = map.createLayer('Next', tileset)

update(t: number, dt: number){       
        
    this.physics.world.collide(this.faune, Next1, ()=>{
        console.log("testing")
        this.scene.stop(),
        this.scene.start('secondmap');
        });

The problem here is that I'm unable to access 'Next1' in order to use it for collision detection with my player character "faune". The error message I get says "Cannot find name 'Next1'. If anyone has any suggestions on how to deal with this situation in Phaser, I would greatly appreciate it.

Thanks, arthur

Answer №1

The issue arises from the fact that you are defining the function Next1 within the create function and then attempting to access it in the update function.
To resolve this, you could define a property within the create function, like so:

this.next1 = map.createLayer('Next', tileset)

In the update function, you can utilize it as follows:

this.physics.world.collide(this.faune, this.next1, () => { 
    // ...
});

To prevent any compiler errors, particularly when using TypeScript, you need to include the property in the class definition.

class myScene extends Phaser.Scene {
    // Use the appropriate data type if known
    public next1:any; 
    ...
}

Alternatively, you can relocate the this.physics ... code back into the create function.

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

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Interactive window allowing the user to closely examine code

Hey guys, I need your help with something Is there a way (PHP / jQuery) that allows me to zoom in on my code? Similar to how lightbox works for images. I specifically want to zoom in on dynamic code while using Yii's CListView. I'm thinking of ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

Tips for making an appended element match the height of an image

After embedding the div .soonOverlay into specific .smallCatalogBlock's, I am facing difficulty in adjusting the height of soonOverlay to match only the height of the img within smallCatalogBlock. Currently, its height extends throughout the entire co ...

The dynamic drop-down menu is giving incorrect values when the onchange function is called

Trying to implement Google Analytics tracking on my dynamic dropdown menu in WordPress has been a bit tricky. I want to be able to track when users click on any of the options and display the name of the selected value, not just the ID. However, I've ...

Code snippet for converting the current webpage into a PDF using Jquery

Looking for guidance on how to convert the current webpage into a PDF using client-side (JQuery) code. The PDF should include all content from the webpage along with a few images if possible. The main requirement is to have all webpage content in the PDF, ...

Alter the browser's URI without having to reload the page

Is there a way to change the browser URL (or URI) without refreshing the page using HTML5 and HTML5Shiv for IE? For example, if I am currently on http://www.example.com but want to transition to http://www.example.com/4f6gt without the need for a full pa ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

Having trouble detecting the Selection event of a Dropdown List upon loading

When a user chooses an option from the dropdown menu, I need to capture the selected item and perform an action: $("#user-list").on("change", function() { var selectedUser = $(this).find(":selected").text(); // Perform action with the selected us ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

exciting command: templateUrl

I am in need of assistance with a particular issue: I am trying to configure settings for an application and would like to utilize the UI-Bootstrap accordion. This is the HTML code I have so far: <accordion close-others="oneAtATime"> <accor ...

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Angular time-based polling with conditions

My current situation involves polling a rest API every 1 second to get a result: interval(1000) .pipe( startWith(0), switchMap(() => this.itemService.getItems(shopId)) ) .subscribe(response => { console.log(r ...

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...