Reputation: 919
I am having difficulty deciding how components (objects of which to add inside of an object) should communicate and alter the data of their "parent" object.
For instance if I had a player object and a collision object within, I would pass the player (parent) object into the collision object and have the collision object change the properties of the player object when appropriate. But how would I go about overriding the collision objects function to alter the player object without creating a new collision subclass?
Could the player parent object pass in a callback function to run for when the collision object detects a collision? Would this be a good idea? Basically I would like the player object to hold an array of components and run an update function on all of them.
Also would the best way for a component to communicate with another component be though the player (parent) object that has been passed to it?
Thanks in advance.
Upvotes: 1
Views: 145
Reputation: 7510
There are a lot of design patterns, that you might want to check online. Just search for 'design patterns' and maybe GoF - it's a well established group of authors that made one of the first books about it.
There is no 'perfect' way to do it - everything depends on your structure and ideas of realization.
You could check the Observer
pattern, but I suggest you to read the whole book.
I usually don't like passing a callback so that a child can modify it's parent. Commonly, the tree of inheritance should be in the other direction - the parent one to control it's children. That's why there is a Controller
pattern, which decides what to do with each object.
You could also make them communicate via events or observer, or whatever you wish in order to make the controller class knows that there should be a change in the state.
It really depends on the situation, but I would basically dispatch events and get a common controller that decides what to do and with which node. There is also a State pattern that you may want to check.
Upvotes: 1