Say I have a few base classes: HasPosition supplies a 2D location, and methods t
ID: 659133 • Letter: S
Question
Say I have a few base classes:
HasPosition supplies a 2D location, and methods to "move".
IsDisplayable defines how a class will be displayed in a given graphics library (say, curses), and methods to change its representation.
HasHealth supplies a health value and methods hurt and heal.
If I multiply-inherit all 3 into a single class, Entity, I'll have a class that can be displayed, moved, and hurt (a starting point for a game entity).
This could be added to and mixed to yield any number of classes.
Is there anything wrong with this approach? Is it at all typical to have "top level" classes that are more or less made up of several other base classes?
I'm trying to create reusable set-up to use to create games using Pdcurses, and wondered if this was a good way to set up my classes.
Explanation / Answer
Is there anything wrong with this approach? Is it at all typical to have "top level" classes that are more or less made up of several other base classes?
Yes, and yes.
Historically, it has been common practice among game engine developers to build their game entities in exactly the way you describe. I have, in fact, several well-regarded books that describe an inheritance model for game entities.
However, in the last couple decades, developers observed that inheritance is inherently limiting:
Modifying the game logic to add new features requires modifying the game engine.
Entity relationships must be hard-coded.
Entity data is, by necessity, spread across large areas of memory, incurring large performance penalties for tight per-system update loops. (For example, while doing physics on sets of objects.)
Instead, what has come into vogue among game developers (and for good reason) is data-driven entity systems.
In an entity-component system, there are several performance and extensibility advantages:
Modifying game logic can be done trivially by attaching a new component to an entity.
Entity components can be allocated in batches, to keep similar data close together; this allows, for example, a physics system to quickly perform its calculations on data that literally streams into the CPU's cache, with great performance benefits.
Entity relationships can be defined at run-time, so that entities can be constructed entirely external to the engine, in a scripting engine, or even over the network.
Faster turnaround on new features--new components and component systems touch fewer parts of your codebase, requiring less work in the long run.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.