My game objects generally look like this in a pseudo-javascript
fashion:
function Player(){
this.update = function() {
//logic that should be run per update frame
//physics code I really don't want here
}
}
Player.prototype = new gameObject;
Player.update
is called by a gameObjectManager
that instantiated it, which is basically an array that loops through calling update()
on all objects in it. Fine, this works well enough for update functions that are specific to the object itself.
What I don't want in that function is physics logic. It's causing unnecessary bloat in my code and I'm finding that I have to duplicate a lot of functionality in each unique gameObject
I create. Finding the appropriate class to put this in is difficult, because not all of my gameObjects
need it.
One solution I have toyed with is another class like gameObjectManger
, cleverly named physicsManger
, which will maintain an array of objects that require physics updates, and act upon them directly instead of calling update()
for each.
Or, maybe that code should go into gameObjectManager
itself, I don't know.
My goal is to make applying physics to any arbitrary object in the gameworld
be as easy as setting
player.physics = true;
The objects ideally should not know or care about physics code, just that they can be acted upon by it.
My recommendation is to just separate it to two functions. Have a updateLogic()
function and an updatePhysics()
function. Then for physicsless objects leave the updatePhysics()
function empty. You could add a physicsObjectManager
if you like, but I would just have your gameObjectManager
call each function for each object.
I'm presuming that by 'bloating my code' you mean in terms of reading and maintaining it, not in terms of performance. I highly recommend using helper functions more often (subdividing a function into smaller, reusable component functions) if you find you are writing similar or identical code often.
I don't know what language you are developing in, but this also sounds like a perfect time to use Object Inheritance. This will make your classes much less redundant, and more structured. You may also find that using inheritance also makes the project easier for you to understand and work effectively with.