Troubleshooting: The canvas texture in Phaser 3's Update() function is not functioning

I've been attempting to transform this tutorial into Phaser 3: but have encountered an issue with the update() function not working. I also tried using the refresh() function, but that didn't solve the problem either. In my file a.ts, I have created a canvas texture:

this.textures1 = this.textures.createCanvas('canvastextures1', 450, 170)
this.land1 = this.textures.get(MAPOPTIONS.BASE1_NAME).getSourceImage()
this.textures1.draw(0, 0, this.land1)
this.textures1.context.globalCompositeOperation = 'destination-out'

Then, in my file b.ts, within the overlap() function:

this.activeTextures = this.textures.get('canvastextures1')
this.activeTextures.context.beginPath()
this.activeTextures.context.arc(Math.floor(overlap2.x - tile.getTopLeft().x), Math.floor(overlap2.y - tile.getTopLeft().y), 50, 0, Math.PI * 2, false)
this.activeTextures.context.fill()
this.activeTextures.update()

Any suggestions or ideas would be greatly appreciated. Thank you.

Answer №1

Check out this demo-code showcasing my approach to creating a canvas with terrain/land destruction collision mechanics.
It covers all the key points, excluding file splitting. Hope you find it helpful.

Bomb & Crater Demo:

// Code formatted for clarity on stackoverflow
document.body.style = "display: flex;flex-direction: column;";    

class Scene extends Phaser.Scene {

        constructor() {
            super({ key: 'testScene' });
        }

        create() {

            // Start  -- GENERATE TEXTURE just for demo
            let helperGraphics = this.make.graphics({x: -250, y: -105, add: false});
            helperGraphics.fillStyle(0xEAEAEA, 1);
            helperGraphics.fillRect(0, 20, 500, 100 );
            helperGraphics.generateTexture('land', 500, 210);
            // End  -- GENERATE TEXTURE just for demo

            this.baseLand = this.textures.get('land').getSourceImage()
            this.baseCanvas = this.textures.createCanvas('currentLand', 800, 200);
            // Create initial Land Texture
            this.baseCanvas.draw(0, 0, this.baseLand);
            this.baseCanvas.context.globalCompositeOperation = 'destination-out';
            // load image to scene
            this.land = this.add.image(0, 20, 'currentLand').setOrigin(0);
            this.physics.add.existing(this.land);
            this.land.body.setImmovable(true);
            this.land.body.setAllowGravity(false);

            // init bomb
            this.createBomb();

        }
        // creates always new bomb
        createBomb(bomb, land) {
            this.bomb = this.add.circle(Phaser.Math.Between(100, 300), -5, 5, 0x6666ff);
            this.physics.add.existing(this.bomb);

            this.physics.add.overlap(
                this.bomb,
                this.land,
                this.overlap,
                this.shouldProcess, this);
        }
        // action on overlap
        overlap(bomb, land) {
            // remove bomb on contact
            let {x, y} = bomb.body.center;
            bomb.destroy();
            // create crater on old bomb position
            this.createCrater({x, y});
            // create new bomb 
            this.createBomb();
        }
        // checks if bomb hits land
        shouldProcess(bomb, land) {
            let x = Math.floor(bomb.body.center.x - land.x);
            let y = Math.floor(bomb.body.center.y - land.y);
            return this.textures.getPixelAlpha(x, y, "currentLand") === 255;
        }
        // create crater 
        createCrater({ x, y }) {
            this.baseCanvas.context.beginPath();
            this.baseCanvas.context.arc(x- this.land.x, y - this.land.y, 23, 0, Math.PI * 2, false);
            this.baseCanvas.context.fill();
            this.baseCanvas.update();
        }
        
        update(){
        
            if(this.bomb && this.bomb.body.y > 160){
                this.bomb.destroy();
                this.createBomb();
            }
        }
    }

 var config = {
    type: Phaser.AUTO,
    width: 500,
    height: 153,
    physics: {
      default: "arcade",
          arcade: {
              gravity: { y: 100 }
          }
    },
    scene: [Scene],
    banner: false
}; 

new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cabaa2abb9afb88af9e4ffffe4f8">[email protected]</a>/dist/phaser.js">
</script>

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

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

How to show specific images by clicking on particular items in Ionic 3 on a separate page

Can someone assist me with displaying specific images from a slider gallery? I am struggling to figure out how to show only the January edition when clicking on it in eighteen.html, while hiding the February and March editions. It has been 2 days of unsucc ...

Mastering Typescript generics for accurate mapping between keys and values through indirection

I've been struggling to understand how to create a specialized mapper that can indirectly map methods based on one object's values corresponding to another object's keys. The mapper used in the code snippet below is not mine; it's an e ...

Why should TypeScript interfaces be utilized in Angular services for defining type information?

What are the benefits of creating an interface for an Angular service as opposed to simply exporting the service class and using that for type information? For example: class Dashboard { constructor(ui: IUiService){} } vs class Dashboard { cons ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

Implementing cursor-based pagination in Next.js API Route with Prisma and leveraging the power of useSWRInfinite

I am working on implementing cursor-based pagination for a table of posts using Next.js API Route, Prisma, and useSWRInfinite. Currently, I am fetching the ten most recent posts with Prisma in a Next.js API Route and displaying them using useSWR, sorted b ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

How come TypeScript remains silent when it comes to interface violations caused by Object.create?

type Foo = { x: number; }; function g(): Foo { return {}; // Fails type-check // Property 'x' is missing in type '{}' but required in type 'Foo'. } function f(): Foo { return Object.create({}); // Passes! } functio ...

Retrieve the value from an HTML class using Angular

The Person Object has a field called schoolId, but the School object (not shown here) contains the schoolName. I want to display the schoolName in the table data cell instead of the schoolId from the Person Object. How can I achieve this? <tr *ngFor=& ...

What is the proper way to incorporate types in a universal function?

Encountering an issue with TypeScript while using a universal function export const createNewArray = <T>( arr: T[], keyId: keyof T, keyTitle: keyof T, ) : [] | TValue[] => { const arrayAfterMap = arr.map((item) => ({name: item[ ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

If "return object[value1][value2] || default" does not work, it means that value1 is not a recognized property

Within my code, there is an object literal containing a method that retrieves a sub-property based on a specific input. If the lookup fails, it should return a default property. //private class, no export class TemplateSelection { 'bills'; & ...

Is it possible for lodash's omit function to return a specific type instead of just a partial type?

Within the following code snippet: import omit from "lodash/fp/omit"; type EnhancerProps = { serializedSvg: string; svgSourceId: string; containerId: string; }; const rest = omit(["serializedSvg", "containerId"])(props); The variable 'rest&a ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Issue with React Context Provider failing to set value

I am currently diving into React context hooks and encountering an issue that is puzzling me. I have established a user context with the simple string message of "hello user" as follows: import { useContext, createContext } from "react" export ...

Custom Type Guard Leads to Intersection Type Outcome

Recently, I've been experimenting with Typescript and decided to explore the creation of an innovative Either type that could distinguish between success and failure scenarios. Utilizing a user-defined type guard, I managed to precisely narrow down th ...

Ways to confirm the visibility of a web element on the screen with serenity-js

In the current project, I am utilizing the Serenity-js BDD framework with a screenplay pattern approach. However, I am encountering an issue when attempting to assert the visibility of an element on a web page using the "that" method from the Ensure class. ...

Manage both the return of an observable and the setting of a value within a single method using

I am in need of a service that can both return an observable and set a value to a field within the same method. The current implementation of my userService.getUserDetails() method is as follows: private requestUrl: string; private bic: string; private i ...

The TypeScript variable is automatically assigned the type 'any' since it does not contain a specified type annotation

Issue: The variable 'environment' is implicitly assigned the type 'any' because it lacks a specific type annotation and is referenced within its own initialization code. Code Snippet: export const environment = { production: fals ...