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.