Hey guys, this is a general game programming question, but I’ll try to illustrate with a specific example just so it’s easier to understand.
Suppose you have a survival game. There are items that player may interact with. For example, we have these two classes:
Foodstuffs (apple, banana, grapes, and so on)
Vehicles (car, truck, and so on)
The common link that Foodstuffs and Vehicles share is that they can both be interacted with.
So, as I understand there are two main approaches: I add an “interactable” component to both the class Food and the class Vehicle.
Alternatively, I derive Foodstuff and Vehicles from a parent class: Interactable Object class. And in that parent class lives an OnInteracted function. Perhaps some other shared functions may exist, but for example I think a single commonality is enough.
As far as I can tell, the difference between inheritance and component structure here is in ergonomics? With components I need to remember to add the component to anybody who needs it, which does have some room for annoying human error.
With inheritance I guess the worry is that I could possibly spin a tangled web, but I think so long as the chain is only 1 or 2 layers deep, what is the problem? Should some child class need to override a function that allows for all the flexibility I need, right? And if over the course of development, I realize that a banana is actually in a class of its own, then I can just change the parent class, no problem. Right?
So, my major question is - is it just a matter of ergonomics? Are there performance or other technical considerations I am unaware of?
In the past I’ve used something like a state pattern to handle input. I have a Base State class that has some common functions like OnConstructed and HandleSpacebarInput. Depending on the Child State class that is currently active, then I can easily map the same input functions many different ways. This also chunks my code in a very intuitive and easy to debug way.
I see the same approach being viable to handling interactable objects. If I collide with a game object, we query its class. If it is interactable object class, we can call its OnInteracted function, and the child instance is going to add additional stuff on top of the parent’s function or override it entirely if necessary.
Another approach might be that we just send an interface message to the collision object, and should it implement the interface it can do whatever it wants. But if my Apples, Bananas, Pears and Kiwis are only differentiated by their data values (i.e banana is 10 calories, apple is 12, and each has its own sprite image), then it seems like making each of these things a separate game object that has to get a litany of components and each subscribe to interfaces is a lot more work?