Motivation
In games command pattern is often applied to:
- Create rebindable input controls;
- Support undo or time rewind mechanics;
- Decouple playable characters from direct user input by having player input create identical commands to that of an AI. This enables the game to switch control of characters between different players or AI and reduces the complexity and size of the codebase, by forcing developers to use common code for both player and AI actions.
- One way of synchronizing multiplayer games is to pass all the input of different players over the network and run simulation on all ends separately. Timestamped commands can be used to make sure all the actions are applied in correct order in all ends of the communication. This is more popular in RTS games with large numbers of units, as instead of synchronizing the complete state of every unit every frame, only a few commands have to be sent over the network.
Outside games commands are often used as an object-oriented replacement for callbacks. Callbacks are functions that are registered somewhere and can be called at a later point. As command pattern turns actions into objects, this means commands can be stored, executed at a later point, undone or even passed on to a different process over network.