This is one of the hardest part of game-development according to my brain apparently, I have a hard time figuring out how to handle interaction between multiple objects that are derived from the same base-class.
Let me try to explain it. Lets say I have a few objects that all derives from the parent-class "GameObject":
- Bullet
- Player
- Enemies
- Power-Ups
- Sword Slash Bounding-box
- Tiles - such as platforms ect.
Here we have a lot of game objects, that shares the common attributes and functions which are stored inside an vector<GameObject*> which contains all the objects present on the map.
So far so good! But here is when my brain just implodes, trying to determine what interacts with what without looping EVERY object and dynamic-casting everything!
Lets assume I have some magical query function that can fetch an array of nearby objects from any arbitrary object!
What I do at the moment is something along the lines:
GameObject has two virtual methods called getType() and getSubType() which returns a string.
When queering close by objects, I iterate through the vector checking if anyone is colliding ( or whatever triggers the interaction ) and if they are I check what type they are, to determine if they should react to the colliding object.
I often put the interaction code inside of the object - i,e Bullets interacts with either Player or Enemy ( depending on the subtype ), Power-Ups interact with the Player and so on:
Example:
// Inside of Player-class
void update( float dt ) {
/* Code */
vector<GameObject*> v = mWorld.fetchObjects(this->x,this-y,50);
for( GameObjects* o : v ) {
if(o->collide(this)) {
o->interactWith(this); // Object "o" will check "this"->getType() and determine what it will do.
}
}
}
Though I am a bit afraid I might do some unecessary already done collision checks+interactions - but shouldn't be a problem as long as I define what object interacts with what! I.E Bullet checks for Enemy-collisions but Enemies don't check for Bullets ( a bit weird isn't it? ).
The problems I feel with this approach is that:
1) It's not clear of what object should check for what collision - Enemy vs Bullets or Bullets vs Enemies?
2) Not flexible when more and more object-types are introduced.
I have tried searching for clean, simple ( low on complexity and code-base ) 2D projects to see how they handle all the objects interaction - especially when they are "anonymous" as in they are stored in a vector<GameObject*>.
There must be a better way ( without resorting to Component systems or a shit ton of dynamic-casts ) to deal with interacting with different types of objects!
Hopefully someone will spread some light on this topic because my searches have failed me.
Kind regards,
Moonkis