Combining FSMs and decision trees

Given the previous recipes' ease of implementation and learning, we can combine them to develop a powerful decision-making system with benefits from both worlds, making it a very powerful technique in many different scenarios.

Getting ready

We will learn how to make modifications and develop child classes in order to create a finite-state machine that is capable of creating complex transitions based on decision trees.

How to do it...

This recipe relies on creating a couple of child classes from the one we already know and making a little modification:

  1. Create a new action class that holds a reference to a state:
    using UnityEngine;
    using System.Collections;
    
    public class ActionState : DecisionTreeNode
    {
        public State state;
    
        public override DecisionTreeNode MakeDecision()
        {
            return this;
        }
    }
  2. Implement a transition class that is able to hold a decision tree:
    using UnityEngine;
    using System.Collections;
    
    public class TransitionDecision : Transition
    {
        public DecisionTreeNode root;
    
        public State GetState()
        {
            ActionState action;
            action = root.MakeDecision() as ActionState;
            return action.state;
        }
    }
  3. Modify the LateUpdate function in the State class to support both transition types:
    public void LateUpdate()
    {
        foreach (Transition t in transitions)
        {
            if (t.condition.Test())
            {
                      State target;
                if (t.GetType().Equals(typeof(TransitionDecision)))
    
                    TransitionDecision td = t as TransitionDecision;
                    target = td.GetState();
                }
                else
                    target = t.target;
                target.enabled = true;
                this.enabled = false;
                return;
            }
        }
    }

How it works...

The modification on the State class lets us deal with the new type of transition. The new child classes are specific types created to trick both systems and obtain the desired result of having an action node that doesn't do anything itself, but returns a new state to be activated after choosing with a decision tree.

See also

Refer to the following recipes:

  • Choosing through a decision tree
  • Working a finite-state machine
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.120.187