What are the reasons for and against a game object drawing and updating itself? For example, if you have a game where the player has a position on screen, why not have an all-encompassing class:
public class Player {
private int x, y, xVelocity, yVelocity;
private Sprite s;
//...
public Player() {
// load the sprite here, somehow?
}
public void draw(CustomGraphicsClass g) {
g.draw(s, x, y);
}
public void update(long timeElapsed) {
x += (xVelocity * timeElapsed);
y += (yVelocity * timeElapsed);
}
}
What is wrong with this design? What are the downfalls or concerns? How would you better write something like this, or better architect this type of thing in a game?
Also, somewhat connected, how would you implement loading that Sprite image?
And furthermore, how would you then implement collision between two Player
s?
(I should probably separate these extra two questions into new questions, huh?)
It couples all of your rendering and logic code together when they have little in common beyond being conceptually tied to the same "entity". As your class gets bigger, you can find yourself with a huge monolithic Player
that's a nightmare to maintain. Splitting out along domain boundaries (rendering, AI) makes it more manageable without having to give up much since those domains don't have a lot of overlap.
Beyond maintainability, there's some other considerations:
If you want to process rendering and AI on different threads, mixing their state into the same class is just begging for nasty multi-threading problems.
If you're using a language like C++, highly-coupled classes like this can kill your compile times.
Depending on how your code and objects are laid out in memory, splitting objects into separate components for each domain can give you better cache coherency and much better performance.
Here's lots more info if you're curious.
A possible drawback might be a violation of seperation of concerns. I would think that, ideally, the objects shouldn't know how they're rendered, so that the rendering engine could be tweaked seperately from the game objects...though, in practice, it may be that these things are often too interdependent to be seperated in this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With