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.