lundi 26 février 2018

C# design pattern when you find yourself in need of events to be executed in specific order

I'm making a game in C# where two different classes are notified via events when the player moves.

One of those classes is the RenderGrid, as soon as the player moves the RenderGrid will instantiate only the new game tiles now visible on screen. It also contains two vectors describing the bottomLeft and topRight corners of the grid that is currently being rendered

The other is the WorldManager class, which as soon as the player moves, will check if there's the need to load and create new chunks of the game world. To do so, it needs to check the corners of the RenderGrid to ensure they're still inside the boundaries of already loaded chunks.

And here is the problem, since WorldManager depends on the event being handled first on RenderGrid and then on WorldManager thus breaking the event pattern

In pseudo-code, here's RenderGrid:

public class RenderGrid {

    public Vector2 bottomLeft;
    public Vector2 topRight;

    public RenderGrid() {
        Player.onPlayerMoved += playerMoved;
    }
    ~RenderGrid() {
        Player.onPlayerMoved -= playerMoved;
    }

    private void playerMoved(Vector2 delta, Vector2 position) {
        // updates the bottomLeft and topRight corners
    }
}

And WorldGrid:

public class WorldGrid {
    public WorldGrid() {
        Player.onPlayerMoved += playerMoved;
    }

    ~WorldGrid() {
        Player.onPlayerMoved -= playerMoved;
    }

    private void playerMoved(Vector2 delta, Vector2 position) {
        // it needs the corners of the renderGrid, but since those are also updated when player moves, we can't be sure
        // wheter they've been updated here or not
    }
}

Using a separate event to notify that the RenderGrid corners have been updated and listening to it seems like sure spaghetti and I'm not sure how to proceed from here

Aucun commentaire:

Enregistrer un commentaire