Jump to content
  • Advertisement
Sign in to follow this  
Artificial_Idiot

Finite State Machine using Command Pattern?

This topic is 917 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

class EnemyController : MonoBehaviour
{
    IState PatrolState;
    IState AttackState;

    StateMachine FSM;

    void Awake()
    {
        //The state has an Action delegate as an argument called Enter, Execute, Exit in order
        PatrolState = new State(StartWalkingAnim, Patrol, StopWalkingAnim);
        //an overloaded one with only execute as an argument
        AttackState = new State(Attack);

        FSM = new StateMachine();
        FSM.SetCurrentState(AttackState);
    }

    void Update()
    {
        FSM.Update();
    }

    private void StopWalkingAnim()
    {
        //stop walking animation
    }

    private void StartWalkingAnim()
    {
        //stop walking animation
    }

    private void Patrol()
    {
        //if (player.Onsight) 
        //   FSM.ChangeState(Attack)

        //movement.Patrol();
    }

    private void Attack()
    {
        //if (!player.Onsight) 
        //   FSM.ChangeState(Idle)

        //AttackController.Attack();
    }

}


The benefit I could see here is all the functions has a direct access to member variables so no passing of reference is necessary. and also no need for seperate class for each state. this is inspired by the command pattern in WPF and Xaml databinding

 

what do you guys think? do you think this will scale? if not whats the way to make this better? or something is fundamentally wrong here?

Edited by Artificial_Idiot

Share this post


Link to post
Share on other sites
Advertisement
I have been using state machines with Unity and thing that is definately a good way to go.

I would, however, make a state a separate class you instantiate and pass the EnemyController into.


PatrolState = new PatrolState(this);

Having all of your states bundled as methods will make your code hard to reuse. If you have your EnemyController implement an interface, something like IMovingObject. Then you can make PartrolState accept an IMovingObject in its constructor so you can resuse PatrolState on anything that is an IMovingObject.

I would also not have a state for specific animation. I would let mechanim take care of the animating. IMHO, you state machine should function identically with or without animations. That way your animation and art can be updated without effecting gameplay.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!