Invoking a subclass's method within a base class in Typescript

Currently, I am in the process of developing a small game project and I am facing a particular challenge that I need a solution for.

Within my code, I have a base class called 'Entity' which contains essential methods for its subclasses (objects) such as movement and model rendering functions that are common to all subclasses.

  • Entity -> Base Class,

    • SpellObject -> Subclass / Extends Entity

    • PlayerObject -> Subclass /extends Entity

    • UnitObject -> Subclass / Extends entity

One of the key requirements in my code is that when a collision occurs in the default movement method of the Entity class, I want to trigger a subclass-specific method called onCollisionHit, which is unique for each XXXObject (where XXX could be any object).

Below is a snippet of my code:

Entity:


class Entity
{
    constructor(obj: EntityInterface)
    {
        ///
    }

    public doMove(...):void
    {
        // SpeedX SpeedY...
        // ...
        if (collisionHit)
            // getSubclass f.e PlayerObject.onCollisionHit()

        this.addPosition(speedX, speedY)
        //...
    }

    // ....

SpellObject/PlayerObject/...


export class xxxObject extends Entity
{
    constructor(obj:XXXInterface)
    {
        // ...
    }

    public onCollisionHit(...):void
    {
        // Do something (for SpellObject ->Call spell Disapear, for Player set MovementX/Y to 0..
    }

The challenge I am facing is how to invoke the onCollisionHit method from the base class in this scenario. One possible solution I have considered is by linking the subclass instance to a variable in the base class.

  • In Entity -> protected subclass;

  • In xxxObject -> this.subclass = this; -> in doMove() -> when collision hit call -> if (this.subclass) this.subclass.onCollisionHit()

I am uncertain if this solution is optimal as it may lead to memory wastage.

Thank you in advance for your assistance.

Answer №1

Transform onCollisionHit into an abstract method within the abstract class Entity. This change ensures that every subclass of Entity must implement the method, preventing the instantiation of a raw Entity.

abstract class Entity
{
    constructor(obj: EntityInterface)
    {
        ///
    }

    public doMove(...):void
    {
        // SpeedX SpeedY...
        // ...
        if (collisionHit)
            this.onCollisionHit();

        this.addPosition(speedX, speedY)
        //...
    }

    public abstract onCollisionHit():void;
    // ....

Now, you can utilize this.onCollisionHit() within the method implementations of Entity. In cases where you need to instantiate an Entity directly, you can opt for a default (possibly empty) implementation of onCollisionHit() and have subclasses override it.

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 method to extract information from an ever-changing external JSON file?

I am currently in the process of developing a discord bot using discord.js, and one of the features I am trying to implement is a command that displays the current bitcoin price. To achieve this, I am utilizing the CoinDesk API which provides the necessary ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

What could be causing my JavaScript/jQuery code to malfunction when dealing with checkboxes?

My code is supposed to select and disable checkboxes based on which radio button is clicked. For example, when Zero is selected, all checkboxes should be highlighted and disabled, except for the zeroth checkbox. However, this behavior does not consistent ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

dividing values for future angular use

Within my code, I have the following snippet: color: {{item.color}} This setup functions well when dealing with single items. However, there are instances where I encounter a value such as: white|black Is there a way to separate these values into indiv ...

Error: JSON unexpected token ' at position 2 - Solution for fixing this issue

Encountering a recurring JSON error where the user input from a textbox is being passed in JSON for assigning class level permissions in a parse server. var cc = "role:" + user; var jsonParam = "{ 'classLevelPermissions' : { ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

Executing tasks in a While loop with NodeJS and attaching actions to a Promise

I am relatively new to incorporating Promises in NodeJS. My current task involves creating a promise dynamically with multiple actions based on the characters found in a string. //let actions = []; getPromise = get(srcBucket, srcKey); // Retrieve the imag ...

"Step-by-Step Guide: Displaying a New Component When a Table Row is

I am currently working with an API to populate a table within the router outlet, but I would like to know how I can load a different component that displays the details of a selected row. For example, if the table contains a list of equipment, I want to be ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

Querying Mongoose Nested Data in Express: A Comprehensive Guide

I need to retrieve the "stocked" boolean value for item "4" belonging to user "456" from my mongoose data collection. However, when I try to query for this specific information, I end up receiving the entire user object instead. Data: data = [{ use ...

Can we divide an animation in Three.js according to a model's individual parts?

Recently delving into the world of three.js, I have encountered a project with specific requirements: Load a humanoid gltf model Play various animations on the model Stop or play animation for only the head part of the gltf model without altering animatio ...

"Clicking on the dropdown menu will consistently result in it collapsing

When it comes to a DropDown menu, the typical expectation is that when an option is selected, the menu will collapse. However, in my situation, I do not want the dropdown menu to collapse if the user is attempting to log in and clicks on the Username and P ...

The retrieval process is unable to receive a response from the server

Question: I am encountering an issue with the fetch API in the client-side code. Here is the snippet of the code: window.fetch('/signup', { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlen ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

Error detected in ASP.NET MVC due to a Javascript runtime issue

After creating a new ASP .net mvc 2 web application using the default template in Visual Studio 2008, I wanted to test how the document.ready function fires. In the Site.Master file, I included the jQuery Scripts in the following manner: " <script src ...

Exploring the interactivity of Vue3 Composition API props!

Currently, I am monitoring two props on a child component (basicSalaryMin and basicSalaryMax). Once the value changes, my next step is to update a reactive value on the parent component (data.companyModels, which is also passed to the child component as a ...

Calculate the total price using jQuery

I’m a beginner in JavaScript and I’ve hit a roadblock. I have a plus and minus button that adds up product quantities, but I need the total price to reflect this as well. Some products can only be purchased in multiples of 2, 5 or 10. Here is the HTML ...

Strategies for ensuring a promise is fulfilled before moving on to the next iteration in a never-ending for loop in JavaScript

I've been exploring ways to ensure that a promise is resolved before moving on to the next iteration in a for loop. One suggestion was to use the setInterval() function instead of a for loop, but this isn't ideal since it's hard to predict w ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...