Unity检查动画Animator状态

2019-03-30  本文已影响0人  远行_2a22

Unity射击游戏,在换弹动画中,因为想实现在换弹成功后,子弹数再更新,而且换弹过程中要禁用射击。因此必须知道当前的换弹动画是否结束。

方法1:AnimatorStateInfo

在脚本中添加代码

 //检查是否正在播放reload动画.
 AnimatorStateInfo stateinfo = anim.GetCurrentAnimatorStateInfo(1);   # 参数表示动画层的id
 bool play_ing_flag = stateinfo.IsName("handgun_combat_reload");

当处于状态handgun_combat_reload,则stateinfo.IsName返回true

注意

完整代码如下:

  // 装弹函数
 void ReloadEvent()
 {      
      // 更换弹药
            if (load_bullet_success == 0)  // 0 表示开始装弹,则播放装弹动画  
                anim.SetBool("reload_bullet", true);
            else   // 注意,不能判断if (load_bullet_success == -1)  ,因为当装弹中状态为1时,因为没有"reload_bullet" = false,永远无法播放完毕,始终停留在装弹动画
                anim.SetBool("reload_bullet", false);

            //检查是否正在播放reload动画.
            AnimatorStateInfo stateinfo = anim.GetCurrentAnimatorStateInfo(1);
            bool play_ing_flag = stateinfo.IsName("handgun_combat_reload");

            //检查是否正在播放reload动画.
            if (load_bullet_success == 0 && play_ing_flag)
                load_bullet_success = 1;  // 1表示装弹中

            //如果现在没有在装弹,且上次为装弹中, 表示装弹结束
            if (load_bullet_success == 1 && (!play_ing_flag))
                load_bullet_success = 2;   //表示装弹结束
}

方法2:继承StateMachineBehaviour

Animator的每个状态都可以挂载脚本,将脚本load_bullet.cs挂载在对应的状态上即可。代码如下

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

public class load_bullet : StateMachineBehaviour
{
    private GameObject player;


    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        
        Debug.Log("------OnStateEnter------------");
    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    //override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Debug.Log("-------------OnStateExit-----------------");
    }

    // OnStateMove is called right after Animator.OnAnimatorMove()
    //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    // Implement code that processes and affects root motion
    //}

    // OnStateIK is called right after Animator.OnAnimatorIK()
    //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    // Implement code that sets up animation IK (inverse kinematics)
    //}
}




参考:

上一篇下一篇

猜你喜欢

热点阅读