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

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

Creating an extended class in Typescript with a unique method that overrides another method with different argument types

I need to change the argument types of a method by overriding it: class Base { public myMethod(myString: string): undefined { return; } } class Child extends Base { public myMethod(myNumber: number): undefined { return super.m ...

Having trouble declaring custom pipes in Angular

A new pipe named 'shortend.pipe.ts' has been created within the app folder. import { PipeTransform } from "@angular/core"; export class ShortendPipe implements PipeTransform { transform(value: any, ...args: any[]) { return ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Flashing Screens with Ionic 2

I am currently dealing with a situation where my login page and homepage are involved. I have implemented native storage to set an item that helps in checking if the user is already logged in (either through Facebook or Google authentication). The logic fo ...

Guide to accessing and modifying attributes of Ionic components in TypeScript file

I am curious about how to manipulate the properties or attributes of an Ionic component from a TypeScript file. For example, if I have an input component on my HTML page: <ion-item> <ion-input type="text" [(ngModel)]="testText"></ion ...

Encountering a NoEmit error with .d.ts files when using Webpack, tsconfig, and dynamic imports

I'm struggling to grasp the interaction between webpack, tsconfig, and .d.ts files in my project. This is how my project structure looks: The ScriptsApp directory includes an @types folder structured like this: Here's my tsconfig.json configur ...

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Tips for injecting a service into a class (not a component)

Can you inject a service into a class that is not a component? Consider the following scenario: Myservice import {Injectable} from '@angular/core'; @Injectable() export class myService { dosomething() { // implementation } } MyClass im ...

The presence of a setupProxy file in a Create React App (CRA) project causes issues with the starting of react-scripts,

I have implemented the setupProxy file as outlined in the documentation: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/address', proxy({ target: 'http ...

Comparison between Destructuring in TypeScript and JavaScript

Starting my journey with TypeScript after a background in JavaScript. In the realm of modern JavaScript, one can easily destructure objects like this: let {n,s} = {n:42, s:'test'}; console.log(n, s); // 42 test Assuming TypeScript follows su ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Angular - Implementing *ngIf based on URL parameters

Is it possible to display an element based on specific queryParams included in the URL? For example: ngOnInit() { this.route.queryParams.subscribe(params => { console.log(params); }); } If I want to achieve something similar to this: ...