0

I'm building a project (small game) and i'm trying to find solution for my issue.

I have code where i use base class Entity which has necressary methods for subclasses (objects) like movement, model rendering etc... Functions which are used in all other subclasses F.e

  • Entity -> Base Class,

    • SpellObject -> Subclass / Extends Entity

    • PlayerObject -> Subclass /extends Entity

    • UnitObject -> Subclass / Extends entity

In entity i have default movement method where i check collision but when the collision is hitted, i want to invoke subclass method onCollisionHit which is defined in XXXObject (For every object i need separated code)

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..
    }

How can i invoke onCollisionHit from base class in this example? One possible solution i found is to link subclass instance to variable of base class

  • in Entity -> protected subclass;

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

Im not sure if it is only a solution by wasting memory.. Thanks all for response.

1 Answer 1

1

Make onCollisionHit an abstract method of Entity, and make Entity itself abstract, since you seem to expect every Entity subclass to implement the method and presumably you should never be able to instantiate just 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;
    // ....

Then you can use e.g. this.onCollisionHit() from within Entity method implementations. If you have need to instantiate Entity instead of a subclass, you can ditch the abstract idea and just have a default (empty?) implementation of onCollisionHit() and have subclasses override it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, this is exactly what i was looking for. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.