I've been writing my own game engine and I was wondering the correct way to handle my game objects. Each game object is different. The only thing they have in common is a set of operations to handle their components. With that said, each game object will have different components that do different things. Ex: game object 1 has input, physics and display components; object2 has only a display component. I was wondering if it was best to
- Loop around the list of objects and call an "update" on each of them and then run each "update" for each component the object holds; or
- Have a list of components in my game loop and check for each component if they have the current component. If so run it, otherwise move on...
I see benefits and harm to both strategies.
- Benefit of 1 is that there isn't a lot of overhead, but things might get out of sync;
- Strategy two is basically the opposite of 1...
For sake of simplicity I'm not putting how I'll handle the gameloop tick and I'm using a generic language.
Example of code for 1:
gameLoop() {
forloop on each game object as obj {
obj->update()
}
}
//obj
update() {
foreach component as component {
component->update()
}
}
Example of code for 2:
gameLoop() {
input = &event
forloop on each game object as obj {
if (obj->canHandleInput())
obj->handleInput(&event)
}
forloop on each game object as obj {
if (obj->hasPhysics())
obj->updatePhysics()
}
forloop on each game object as obj {
if (obj->canDraw())
obj->Draw()
}
//audio...
//other components
}
What is the currently the most accepted way to handle objects in a game loop?