The following describes something that happens in my game:
Projectiles should apply effects to whatever character collides with them.
Here the code I have:
for(Collision collision : rigidBody.getCollisions())
{
if(collision.collider instanceof Character)
{
Character character = (Character) collision.collider;
character.getEffects()
.applyAll(effects);
}
}
I am not too fond of instanceof. However, I cannot think of any satisfying way of doing this. I even googled how to replace instanceof but all the examples were rudimentary and did not apply to this situation.
Here of some other ways I thought of doing it and why I dislike them:
- Entity type enum —
Just a poor man’s version of instanceof.
for(Collision collision : rigidBody.getCollisions())
{
if(collision.collider.getEntityType() == EntityType.CHARACTER)
{
Character character = (Character) collision.collider;
character.getEffects().applyAll(effects);
}
}
- Keep a list of all characters —
This also does not scale well because I could keep doing this and have 10-20 (maybe exaggerated) lists for each subclass. Also, my scene, which would store these list, does not care what the subclass is. However, the fields of my scene do need to know, making this complicated.
for(Collision collision : rigidBody.getCollisions())
{
if(scene.getCharacters().contains(collision.collider)
{
Character character = (Character) collision.collider;
character.getEffects().applyAll(effects);
}
}
- Keep a list of all characters #2—
This is just a reverse way of the previous example that does not require casting.
for(Character character : scene.getCharacters())
{
if(rigidBody.getCollisions().contains(character))
character.getEffects().applyAll(effects);
}