欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unity5利用有限状态机实现AI的圆形,扇形检测算法学习笔记

程序员文章站 2022-03-06 14:37:45
...

先在状态机里面把想要人物的状态设置好,设置一个distance变量在敌人脚本中通过计算敌人与player的距离,来改变distance的值,切换不同的状态,我的代码结构大致如下,状态的行为基本都是放在override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) 方法里面的。扇形的话大概也就是在敌人脚本中新增一个最大距离和最大角度,判断主角进入了检测范围内在进行状态机的转换.

unity5利用有限状态机实现AI的圆形,扇形检测算法学习笔记

unity5利用有限状态机实现AI的圆形,扇形检测算法学习笔记

这里直接把代码贴一下,防止自己以后忘记

PatrolState: baseTreeState

    private List<Transform> wayPoints = new List<Transform>();
    private int index = 0;
    private GameObject Path;
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        base.OnStateEnter(animator, stateInfo, layerIndex);
        Path = GameObject.Find("Path");
        foreach (Transform tran in Path.GetComponentsInChildren<Transform>())
        {
            if (tran.gameObject != Path)
            {
                wayPoints.Add(tran);
            }
        }
    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Quaternion targetRot =Quaternion.LookRotation(wayPoints[index].position-npc.transform.position,Vector3.up);
        npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation,targetRot, rot * Time.deltaTime);
        npc.transform.Translate(Vector3.forward * speed * Time.deltaTime);
        if (Vector3.Distance(npc.transform.position, wayPoints[index].position)<accuracy)
        {
            index++;
            index %= wayPoints.Count;
        }
    }

ChaseState : baseTreeState


    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        base.OnStateEnter(animator,stateInfo,layerIndex);
        player = GameObject.FindWithTag("Player");
    }


    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Quaternion targetRot = Quaternion.LookRotation(player.transform.position-npc.transform.position);
        npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation, targetRot, rot * Time.deltaTime);
        npc.transform.Translate(Vector3.forward*speed*Time.deltaTime);
    }

 

EnemyAI: MonoBehaviour

    private GameObject player;
    private Animator anim;
    //望向目标
    private void Start()
    {
        player = GameObject.FindWithTag("Player");
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        anim.SetFloat("distance",Vector3.Distance(transform.position,player.transform.position));
    }

大概效果图就是如下

unity5利用有限状态机实现AI的圆形,扇形检测算法学习笔记

相关标签: AI