Encountering issues with Phaser Sprite body when receiving undefined input

I am having trouble with flicking when I click the mouse. The variable on input.on is returning undefined when I click the mouse. Here is a code snippet that explains my issue. Phaser is a new concept to me.

    w : number;
    h : number;
    velocity:number;
    sprite = null;
    totalDelta = null;

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

    preload(){
      this.w = Number(this.game.config.width);
      this.h = Number(this.game.config.height);
      this.velocity = Number(this.game.config.physics.arcade.gravity.y);
      this.createBG();
    }


    createBG(){
      this.add.image(0,0,'background').setOrigin(0);
    }

    createSprite(){
      var x = this.w * 0.1; 
      this.sprite = this.physics.add.sprite(x ,this.h/2,'sprite').setOrigin(0);
    }

    create(){
      this.createSprite();
      this.input.on("pointerdown",this.flick);
    }

    flick(){
      this.sprite.body.velocity.y = -this.velocity;
    }

Answer №1

One issue that arises is the necessity of passing the correct context to the on event listener. Refer to the documentation for more information.

// Ensure proper context is passed as the third parameter
this.input.on("pointerdown", this.flick, this);

P.s.: Another option is to utilize an arrow function if you prefer not to pass the context. Although not recommended, it serves as an alternative method of coding. Refer to the documentation on arrow functions for more details.

In other words, this approach also functions:

this.input.on("pointerdown", () => this.flick());

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

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Optimizing Angular 2 TypeScript with enableProdMode for JSPM bundling.QRectPreparing Angular 2

I am in the process of developing an Angular 2 application and packaging it using SystemJS/JSPM. During the development phase, I include the app in index.html: <script src="jspm_packages/system.js"></script> <script src="systemjs.config.js ...

What is the best method to store GPS coordinates in the background every 10 minutes?

Is it possible to automatically store GPS location in the background at set intervals (e.g. every 5, 10, or 20 minutes) and save it to localStorage? Thank you! ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

What is the capability of dynamically generating an index in Typescript?

Can you explain why the Typescript compiler successfully compiles this code snippet? type O = { name: string city: string } function returnString(s: string) { return s } let o1: O = { name: "Marc", city: "Paris", [returnString("random")]: ...

Adding React with TypeScript to an existing ASP.NET Core MVC application: A step-by-step guide

Can anyone suggest a reliable method to integrate react components (typescript) in the form of .tsx files into my asp.net core mvc .cshtml pages? I've been encountering issues trying to make it work successfully. Any insights or advice would be greatl ...

Is there a way to reset static data in a TypeScript subclass? (or alternative method for managing global data)

I have a particular set of static data that I would like to access through an API using basic logic. Specifically, this data pertains to metadata about Java classes. My approach involved incorporating the API into a few static methods within a class, alon ...

Creating a report file based on Typescript type checking results

Is there a way or third-party library that can help generate a report file (such as .html, .csv, etc.) after running TypeScript typechecking with tsc? I need to create a report on typechecking in my Next.js Project, capturing all the output from tsc --noE ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

Are push notifications supported in Ionic3?

I've been struggling to set up push notifications in my Ionic3 app for the past couple of days, and no matter what I try, it doesn't seem to work due to the current versions I'm using. Here are my current versions: rxjs: 5.5.11 Angular: 5 ...

Prevent overlapping of range sliders in HTML and CSS

I have designed a range slider with two buttons, but they are overlapping each other. I want to ensure that they do not cross over one another - where the value of the first button should be equal to the minimum value of the second button, and the maximum ...

Typescript is outputting the error message: "cannot be assigned to the type 'IntrinsicAttributes & { children?: ReactNode; }'"

While there has been extensive discussion on this topic, I am unable to get any other solutions from SO to work, or I am struggling to implement them. I am completely new to TypeScript, and here is what I have: import faker from "faker"; import React fro ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

In the realm of Angular and TypeScript, one may encounter an error stating that '"void' cannot be assigned to a parameter of type '(value: Object) => void"

I’m facing difficulties in resolving this issue. I created a web API using .NET, and now I’m attempting to call this API in an Angular project. //movie.ts export class Movie{ ID: number; Title: number; GenreId: number; Duration: number ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

Using Angular2's BrowserDomAdapter as an alternative to JQuery's .has() for analog functionality

Does Angular2's BrowserDomAdapter have a function similar to JQuery's .has(), or is there another method to achieve the same functionality using the available methods? ...

Error Type: nextjs 13 - children function TypeError

Welcome to the Home page: export default async function Home() { # console.log(data) it is populated const { data } = getAllArts(); return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> < ...

Is it advisable to utilize TypeScript interfaces for declaration files and React component prop definitions?

Whenever I create structures for object types, my go-to method is to define them in my declaration.d.ts file like this: type TagsObject = { _id: string; tag: string; } type ProjectData = { _createdAt: string; _id: string; _rev: string; _type: ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...