Unity学习之FSM有限状态机

前言:一个游戏里的一个人物会存在多种状态,那么就需要有一个专门管理这些状态的类。不然会显得杂乱无章,不易于后面状态的增加或者减少。
思路:既然要方便管理,那么首先肯定得有个系统类(专门用来存放所有的状态、状态的增删等功能);然后就是需要把所有的状态都单独写一个类(已达到修改某个状态的时候,其他状态不会受到影响)。

状态管理类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FSMSystem 
{
    private Dictionary<StateID, FSMState> states = new Dictionary<StateID, FSMState>();

    private StateID currentStateID;
    private FSMState currentFSMState;

    public void Update(GameObject npc)
    {
        currentFSMState.Act(npc);
        currentFSMState.Reason(npc);
    }

    /// <summary>
    /// 添加状态
    /// </summary>
    /// <param name="fSMState"></param>
    public void AddState(FSMState fSMState)
    {
        if (fSMState == null) return;

        //if (currentFSMState == null)
        //{
            currentStateID = fSMState.ID;
            currentFSMState = fSMState;
        //}
        if (states.ContainsKey(currentStateID)) return;
        states.Add(currentStateID, currentFSMState);
    }
    /// <summary>
    /// 删除状态
    /// </summary>
    /// <param name="stateID"></param>
    public void DeleteState(StateID stateID)
    {
        if (stateID == StateID.Null) return;
        if (!states.ContainsKey(stateID)) return;

        states.Remove(stateID);
    }
    

    /// <summary>
    /// 执行状态条件转换
    /// </summary>
    /// <param name="transition"></param>
    public void PerformTransition(Transition transition)
    {
        if (transition == Transition.NullTransition) return;

        StateID stateID = currentFSMState.GetStateID(transition);
        if (stateID == StateID.Null) return;
        if (!states.ContainsKey(stateID)) return;

        FSMState fSMState = states[stateID];
        currentFSMState.StateExit();
        currentFSMState = fSMState;
        currentStateID = fSMState.ID;
        currentFSMState.StateEnter();
    }
}

状态基类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum Transition
{
    NullTransition,
    SeePlayer,//发现玩家
    LostPlayer,//玩家脱离视野范围
    AttackPlayer,//攻击玩家
}
public enum StateID
{
    Null,
    Chase,//追逐
    Patrol,//巡逻
    Attack,//攻击
}
public abstract class FSMState
{
    protected Transition transition;

    protected StateID stateID;
    protected FSMSystem fSM;
    public StateID ID
    {
        get { return stateID; }
    }

    protected Dictionary<Transition, StateID> dic = new Dictionary<Transition, StateID>();

    public FSMState(FSMSystem fSM)
    {
        this.fSM = fSM;
    }

    /// <summary>
    /// 增加状态
    /// </summary>
    /// <param name="transition"></param>
    /// <param name="stateID"></param>
    public void AddTransition(Transition transition, StateID stateID)
    {
        if (transition == Transition.NullTransition) return;
        if (stateID == StateID.Null) return;
        if (dic.ContainsKey(transition)) return;

        dic.Add(transition, stateID);
    }
    /// <summary>
    /// 删除状态
    /// </summary>
    /// <param name="transition"></param>
    public void DeleteTransition(Transition transition)
    {
        if (transition == Transition.NullTransition) return;
        if (!dic.ContainsKey(transition)) return;

        dic.Remove(transition);
    }
    /// <summary>
    /// 获取状态
    /// </summary>
    /// <param name="transition"></param>
    /// <returns></returns>
    public StateID GetStateID(Transition transition)
    {
        if (transition == Transition.NullTransition) return StateID.Null;
        if (!dic.ContainsKey(transition)) return StateID.Null;
        return dic[transition];
    }

    /// <summary>
    /// 进入状态
    /// </summary>
    public virtual void StateEnter() { }
    /// <summary>
    /// 退出状态
    /// </summary>
    public virtual void StateExit() { }

    /// <summary>
    /// 状态持续中,,,
    /// </summary>
    /// <param name="npc"></param>
    public abstract void Act(GameObject npc);
    /// <summary>
    /// 状态退出前,,,
    /// </summary>
    /// <param name="npc"></param>
    public abstract void Reason(GameObject npc);
}

巡逻状态:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 巡逻状态
/// </summary>
public class PatrolState : FSMState
{
    /// <summary>
    /// 巡逻路径点集合
    /// </summary>
    private Transform[] paths;
    /// <summary>
    /// 当前巡逻路径点索引
    /// </summary>
    private int index = 0;
    /// <summary>
    /// 移动速度
    /// </summary>
    private float moveSpeed = 0.5f;
    /// <summary>
    /// 玩家
    /// </summary>
    private Transform player;
    public PatrolState(FSMSystem fSM, Transform player) : base(fSM)
    {
        this.player = player;
        paths = GameObject.Find("Path").GetComponentsInChildren<Transform>();
        stateID = StateID.Patrol;
    }

    public override void Act(GameObject npc)
    {
        npc.transform.LookAt(paths[index].position);
        npc.transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
        if (Vector3.Distance(npc.transform.position, paths[index].position) < 1)
        {
            index++;
            index %= paths.Length;
        }
    }

    public override void Reason(GameObject npc)
    {
        npc.GetComponent<Animator>().SetFloat("Speed", moveSpeed );
        if (Vector3.Distance(player.position, npc.transform.position) < 10)
        {
            fSM.PerformTransition(Transition.SeePlayer);
        }
    }
}

追逐状态:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 追逐状态
/// </summary>
public class ChaseState : FSMState
{
    /// <summary>
    /// 移动速度
    /// </summary>
    private float moveSpeed = 2f;
    /// <summary>
    /// 玩家
    /// </summary>
    private Transform player;
    public ChaseState(FSMSystem fSM, Transform player) : base(fSM)
    {
        stateID = StateID.Chase;
        this. player = player;
    }

    public override void Act(GameObject npc)
    {
        npc.transform.LookAt(player.position);
        npc.transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
    }

    public override void Reason(GameObject npc)
    {
        npc.GetComponent<Animator>().SetFloat("Speed", moveSpeed / 2);
        if (Vector3.Distance(player.position, npc.transform.position) >= 10)
        {
            fSM.PerformTransition(Transition.LostPlayer);
        }
        else if (Vector3.Distance(player.position, npc.transform.position) <= 1f )
        {
            fSM.PerformTransition(Transition.AttackPlayer);
        }
    }
}

攻击状态:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 攻击状态
/// </summary>
public class AttackState : FSMState
{
    /// <summary>
    /// 玩家
    /// </summary>
    private Transform player;
    public AttackState(FSMSystem fSM, Transform player) : base(fSM)
    {
        stateID = StateID.Attack;
        this.player = player;
    }
    public override void Act(GameObject npc)
    {

    }

    public override void Reason(GameObject npc)
    {
        if (Vector3.Distance(player.position, npc.transform.position) > 1f)
        {
            if (Vector3.Distance(player.position, npc.transform.position) >= 10)
            {
                fSM.PerformTransition(Transition.LostPlayer);
            }
            else if (Vector3.Distance(player.position, npc.transform.position) < 10)
            {
                fSM.PerformTransition(Transition.SeePlayer);
            }
            return;
        }
        npc.GetComponent<Animator>().SetTrigger("Attack01");
    }
}

状态持有者实现类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    private FSMSystem fSM;
    private Transform player;
    private void Start()
    {
        fSM = new FSMSystem();
        FSMState patrolState = new PatrolState(fSM, player);
        patrolState.AddTransition(Transition.SeePlayer, StateID.Chase);
        patrolState.AddTransition(Transition.AttackPlayer, StateID.Attack);
        //patrolState.AddTransition(Transition.LostPlayer, StateID.Patrol);

        FSMState chaseState = new ChaseState(fSM, player);
        chaseState.AddTransition(Transition.LostPlayer, StateID.Patrol);
        chaseState.AddTransition(Transition.AttackPlayer, StateID.Attack);
        //chaseState.AddTransition(Transition.SeePlayer, StateID.Chase);

        FSMState attackState = new AttackState(fSM, player);
        attackState.AddTransition(Transition.SeePlayer, StateID.Chase);
        attackState.AddTransition(Transition.LostPlayer, StateID.Patrol);
        //attackState.AddTransition(Transition.AttackPlayer, StateID.Attack);

        fSM.AddState(patrolState);
        fSM.AddState(chaseState);
        fSM.AddState(attackState);
    }

    private void Update()
    {
        fSM.Update(gameObject);
    }
}

到此这篇关于Unity学习之FSM有限状态机的文章就介绍到这了,更多相关UnityFSM有限状态机内容请搜索179885.Com以前的文章或继续浏览下面的相关文章希望大家以后多多支持179885.Com!

猜你在找的Unity学习之FSM有限状态机相关文章

这篇文章主要为大家详细介绍了C#实现销售管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
tensorflowjs,在该项目中使用了ml5js这个封装过的机器学习JavaScript类库, 使用起来更简单,本文给大家分享asp.net core 使用 tensorflowjs实现 face recognition
通过从unity内部函数中抽几个出来改造,强制取某个裁切球的级联阴影映射,通过案例给大家详细介绍,文中给出了完整的urp shader代码,对Unity级联阴影知识感兴趣的朋友一
Zookeeper作为分布式的服务框架,虽然是java写的,但是强大的C#也可以连接使用。而现在主要有两个插件可供使用,分别是ZooKeeperNetEx和Zookeeper.Net,个人推荐使用ZooK
Zookeeper分布式锁的原理是巧妙的是使用了znode临时节点的特点和监听(watcher)机制,监听机制很简单,就是我们可以给znode添加一个监听器,当znode节点状态发生改变时(如:
从IE浏览器获取当前页面内容可能有多种方式,今天我所介绍的是其中一种方法。基本原理:当鼠标点击当前IE页面时,获取鼠标的坐标位置,根据鼠标位置获取当前页面的句柄,然
这篇文章简要的说明了如何去修改Unity默认的脚本编辑器,大大提升了灵活性和便捷性,文本有详细的图文介绍,能让你观看的更加清晰,希望对你有所帮助
在Word中可插入文本框,默认情况下插入的文本框中的文字方向为横向排列,对于一些特殊文档的设计要求,需要改变文字方向,本文就详细的介绍一下使用,感兴趣的可以了解一下
这篇文章详细的讲解了如何从0开发出一个Unity3D的小游戏愤怒的小鸟,本文包含大量的图片与文字描述,也含有大量的源代码,可以让你快速入手,希望本篇文章对你有所帮
这个简单的飞行棋游戏主要是讲的方法怎么应用,充分的去理解方法和方法的调用。整体收获还是很大的。感兴趣的朋友可以参考下
本文介绍如何通过C# 程序来扫描并读取图片中的文字,这里以创建一个.Net Core程序为例。下面是具体步骤,供参考。有此需求的朋友可以了解下
这篇文章重点给大家介绍C#实现读写文本文件中的数据的一些知识,读取.txt文件数据的实例代码及写入读取过程完整代码,感兴趣的朋友跟随小编一起看看吧