Player hits "left" arrow on keyboard
A "move camera, x = -10, y = 0" command is generated
The command is enqueued to the general queue of commands
At some point in the future, the "command processor" dequeues the command
It figures out that this is a move camera command, extract the parameters, and sends to, say, the camera class
The camera class moves the camera -10 to the left
Other requirements:
- commands can be serialized to disk and to the network for replay/multiplayer
- processing of commands should be fast - no reflection involved if at all possible
I read about the Command Pattern but every example I see is trivial and would pose problems in a real game, for instance each command has to know about every object necessary to execute it; not only is this not very clean, it'll also pose problems for serialization. My UnitManager is not the same reference as your UnitManager. I don't want a MoveUnitCommand to call the UnitManager, I want the UnitManager to receive MoveUnitCommands and know how to process them himself.
For now, here's what my first attempt looks like:
public interface ICommand {}
public class CommandMoveCamera : ICommand {
public int DeltaX;
public int DeltaY;
}
// other commands
public class Game {
Queue<ICommand> m_commands;
void Update() {
// Say we need to add a CommandMoveCamera
m_commands.Enqueue(new CommandMoveCamera { DeltaX = x, DeltaY = y });
// At some point in the future, the commands are processed:
while (m_commands.Count > 0) {
ICommand command = m_commands.Dequeue();
// how do we branch based on the concrete type?
}
}
}
And the question is in the code, how to branch out based on the concrete type of each command? Efficiently I mean, I can figure out very slow means myself just fine.
I'm sure some of you have implemented similar systems in the past and I'd like to know how you solved this problem.