vendredi 24 avril 2020

In Game Programming (And OOP Generally), When do we Decide to Use the Command vs the State Design Pattern?

I'm reading in Game Programming Patterns that Commands should be used to give directions for actors, and States are used to indicate a single state the actor would be in (standing, jumping, moving, etc).

I'm currently working on a problem in my codebase right now that I can't seem to wrap my head around in a good way. I currently have 3 "Interaction States" that my characters can be in - Passive, Melee Combat, or Ranged Combat.

And there are several what I think of as Commands currently that a character can be in - Moving, Talking, Attacking, etc. But a character can't be attacking in a passive state, or talking in a combat state - my question is do these commands make more sense as Commands or as States, and I can build a concurrent/hierarchical state machine?

Also, should we think of Commands as the actions that move characters from state to state (e.g. if I right click an enemy I pass the "attack" Command into the State constructor to move from "move" state to "attack" state)? I guess I'm just having a hard time conceptualizing what to do here and how states and commands interact.

Example State, would be attached to a character object:

public class MeleeState : InteractionState
{
    public override void HandleInput(Character character, InteractionCommands command)
    {
        base.HandleInput(character, command);

        if (command == InteractionCommands.CHANGETOPASSIVE)
        {

        }
        else if (command == InteractionCommands.CHANGETORANGED)
        {

        }
        else
        {

        }
    }
}

Example Command:

public class Attack : Command
{

    Attack(Character aggressor, Enemy victim)
    {

    }

    public override void Execute()
    {
        base.Execute();
    }

    public override void Undo()
    {
        base.Undo();
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Aucun commentaire:

Enregistrer un commentaire