Code for interaction between objects goes where?

Started by
4 comments, last by Mathmo 15 years, 10 months ago
Hi. I am making a small game and I am having trouble figuring out where I should put the interactions between my objects. Meaning I have created my objects: screen, main character, enemies etc; and I am wondering where I should put the code that allows them to interact with one another. This code shouldn't be in the class files since that affects their reusability. So where should I put the code like the collision detection between my main character and an enemy? Do all the interactions between the objects just go in main? Seems like it would get large very fast.
Advertisement
As a rule of thumb, a method acting on two classes should go somewhere that knows about both of them. Sometimes that's kosher to put on either class (because you can't reuse one without the other sanely), sometimes it goes on a third class above them (collision detection between two objects is handled by the playfield for example), sometimes it goes in a free function.

And sometimes it's replaced by events or messages.

One thing that helped me a lot was learning the concept of data normalization. It's used primarily for database design, but has a lot of good concepts about organizing data (and thus knowledge) efficiently and coherently.
Quote:As a rule of thumb, a method acting on two classes should go somewhere that knows about both of them.

For example my collisions are facilitated by my "World" class. This is because the World knows (and contains) all the objects.
Thanks for the replies. So is a message system typically the more widely used solution?
No.
if it is only a small game, then you could just use functions defined in your main.cpp, ie

bool AreColliding( Character* a, Character* b );

and call those in main. There is no need to go hardcore OOP if you don't need the benefits

This topic is closed to new replies.

Advertisement