Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with the architecture of a game object drawing and updating itself?

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 Players?

(I should probably separate these extra two questions into new questions, huh?)

like image 331
Ricket Avatar asked Jun 08 '10 19:06

Ricket


2 Answers

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:

  1. 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.

  2. If you're using a language like C++, highly-coupled classes like this can kill your compile times.

  3. 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.

like image 117
munificent Avatar answered Sep 20 '22 11:09

munificent


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.

like image 38
Beska Avatar answered Sep 20 '22 11:09

Beska