Implementation of FSM finite state machine

Source: Internet
Author: User
Tags fsm value store

Reference Original address: http://www.manew.com/thread-48266-1-1.html

After viewing so many state machine articles, finally found a understand, here is very grateful to the author. Sure enough to download the code to slowly analyze it.

The common AI logic is simple, all in switch/case form, which is very similar to the simple factory pattern, but our job is to change the schema to Factory mode, which is to change the case to a separate state class.

First, from the simplest state class to illustrate, first a state abstract base class: Fsmstate. All state classes inherit from this base class, such as Patrol classes, attack classes, and so on. As the base class for all state classes, this class will have some behavior for all state classes:

    /// <summary>    ///determine if you need to go to a different state/// </summary>    /// <param name= "Player" ></param>    /// <param name= "NPC" ></param>     Public Abstract voidJudge (Transform player, Transform NPC); /// <summary>    ///perform the current state/// </summary>    /// <param name= "Player" ></param>    /// <param name= "NPC" ></param>     Public Abstract voidExcute (Transform player, Transform NPC);

The function is very simple, if you need to explain it, then private chat ....

Then in order to facilitate the management of each state there will be a number of their own, there is a dictionary used in the judge to deal with the change of state .... In the code below, the dictionary key stores the events that may occur, and the value store is the number of the state you just said. (For example, when you see a player , go chasing, check the code )

protectedDictionary<transition, fsmstateid> map =NewDictionary<transition, fsmstateid>();//define enumerations, assign numbers to possible conversions Public enumtransition{Sawplayer=0,//See playersReachplayer,//close to playersLostplayer,//player out of sightNohealth,//Death}/// <summary>///defining enumerations, assigning number IDs to possible states/// </summary> Public enumfsmstateid{patrolling=0,//Patrol numberChasing,//Chase numberAttacking,//Attack numberDead,//Death Number}

For example, we are in a patrol class judge judgment, when the player is seen, Find the dictionary transition.sawplayer to get its value:FSMStateID.Chasing. The following code does not understand what aicontroller.settransition is okay, just need to know the inside package is the enemy to see the player after the Get a way to chase the player by looking up the dictionary .

     Public Override void Judge (Transform player, Transform NPC)    {        if (Vector3.distance (npc.position, player.position) <= chasedistance)        {/ / notify Controller to see Player up            NPC. Getcomponent<aicontroller>(). Settransition (Transition.sawplayer);        }    }

in each State class, in fact, are just equivalent to fill in the blanks in the judge (state judgment and switching) and excute (state behavior), fsmstate the rest is the dictionary of the various packaging, such as adding a group of key,value what ...., Of course, can also be deleted, children's shoes to package it yourself.

    /// <summary>    ///add an item to a dictionary/// </summary>    /// <param name= "Trans" ></param>    /// <param name= "id" ></param>     Public voidaddtransition (Transition trans, Fsmstateid ID) {if(map. ContainsKey (trans)) {return; } map.    ADD (trans, id); }

  After you finish fsmstate, you need a state machine to manage ... or give the base class FSM first:

  Public classfsm:monobehaviour{protected Virtual voidInit () {}protected Virtual voidfsmupdate () {}protected Virtual voidfsmfixedupdate () {}voidStart () {Init (); }    voidUpdate () {fsmupdate (); }    voidfixedupdate () {fsmfixedupdate (); }}

here or the virtual method, left to posterity (derived class) to fill, posterity only need to rewrite these methods is equivalent to be able to execute in start, update. Then there is a class called ADVANCEFSM inherits it, it is responsible for managing all the state and storing the current state and a number of the current state, FSM is responsible for monobehaior communication. There is a list of the management of the state, and then the Sky ~ ~ method is about the list of ~ ~ such as packaging add elements to the list, through the list to find the need to transition to the new state.

    /// <summary>    ///add status to Linked list records/// </summary>    /// <param name= "Fsmstate" ></param>     Public voidaddfsmstate (fsmstate fsmstate) {if(Fsmstate = =NULL)        {            return; }        //If the list is empty when you insert this state, add it to the list and return            if(Fsmstates.count = =0) {fsmstates.add (fsmstate); CurrentState=fsmstate; Currentstateid=fsmstate.id; return; }        foreach(Fsmstate Iteminchfsmstates) {            if(Item.id = =fsmstate.id) {return;    }} fsmstates.add (Fsmstate); }    /// <summary>    ///converts a new state based on the current state, and the parameters passed/// </summary>    /// <param name= "Trans" ></param>     Public voidperformtransition (Transition trans) {Fsmstateid ID=currentstate.getoutputstate (trans); Currentstateid=ID; foreach(Fsmstate Iteminchfsmstates) {//traverse the status list to find the status that matches            if(Item.id = =Currentstateid) {CurrentState=item;  Break; }        }    }

  However, this class still has class inheritance, that is, to attach to the enemy script: Aicontroller. To initialize all the information in this class, fill in the blanks with just a few virtual methods of the FSM.

 Public classAICONTROLLER:ADVANCEFSM {/// <summary>    ///The init of the base class in Monobehavior.start ()/// </summary>    protected Override voidInit () {//get the player's informationGameobject Objplayer = Gameobject.findgameobjectwithtag ("Player"); Playertransform=Objplayer.transform;    CONSTRUCTFSM (); }    protected Override voidfsmupdate () {Timer+=Time.deltatime; }    protected Override voidfsmfixedupdate () {Currentstate.judge (playertransform, transform);    Currentstate.excute (Playertransform, transform); }    Private voidCONSTRUCTFSM () {pointlist= Gameobject.findgameobjectswithtag ("Patrolpoint"); Transform[] waypoints=NewTransform[pointlist.length]; inti =0; foreach(Gameobject Iteminchpointlist) {Waypoints[i]=Item.transform; I++; } patrolstate patrol=Newpatrolstate (waypoints); Patrol.        Addtransition (Transition.sawplayer, fsmstateid.chasing); Patrol.        Addtransition (Transition.nohealth, Fsmstateid.dead); Chasestate Chase=Newchasestate (); Chase.        Addtransition (Transition.reachplayer, fsmstateid.attacking); Chase.        Addtransition (Transition.lostplayer, fsmstateid.patrolling); Attackstate Attack=Newattackstate (); Attack.        Addtransition (Transition.lostplayer, fsmstateid.patrolling); Attack.        Addtransition (Transition.sawplayer, fsmstateid.chasing); Attack.        Addtransition (Transition.nohealth, Fsmstateid.dead);        Addfsmstate (patrol);        Addfsmstate (Chase);    Addfsmstate (attack); }     Public voidsettransition (Transition t) {performtransition (t); }}

The above is just a personal opinion of this code, what do not understand or wrong welcome to inform, thank you.

To download the code for children's shoes, please go to the reference address mentioned above to download.

Implementation of the FSM finite state machine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.