【问题标题】:How do I use animation events in Unity as conditions?如何在 Unity 中使用动画事件作为条件?
【发布时间】:2016-08-29 04:22:14
【问题描述】:

我正在尝试让“播放此动画时玩家无法移动”检查我的移动方法。

我有一个 3x8 网格的面板用于此应用程序,播放器在面板之间移动。为此,我有 2 个动画:当玩家离开面板时播放 MovingOut,当玩家进入面板时播放“MovingIn”。所以我想要的流程是:

玩家按下移动键→移动被禁用→“MovingOut”播放→播放器的transform.position移动到目标位置→“MovingIn”播放→重新启用移动。

每个动画只有 4 帧。我目前在“MovingOut”的开头有一个动画事件,它将 int CanMove 设置为 0,在“MovingIn”的末尾有另一个动画事件,将 CanMove 设置为 1。

到目前为止,我的代码如下所示:

public void Move(int CanMove)
{
    //this lets me use panelManager to access methods in the PanelManager script.
    panelManager = GameObject.FindObjectOfType(typeof(PanelManager)) as PanelManager;
    animator = GetComponent<Animator>();

    if (Input.GetAxisRaw("Horizontal") == 1 && CanMove == 1) //go right
    {
        movingToPanel += 1;

        if (IsValidPanel(movingToPanel))
        {
            //play animation MovingOut
            animator.Play("MovingOut");
            transform.position = panelManager.GetPanelPos(onPanel + 1);
            onPanel += 1;
        }
        else
        {
            movingToPanel -= 1;
        }
    }
    //else if( ...the rest of the inputs for up/down/left are below.
}

我在动画制作器中设置了 MovingIn,以便它在 MovingOut 动画结束时播放,这就是我不在脚本中调用它的原因:

我一生都无法弄清楚如何将 CanMove 传递到方法中,而不必在调用方法时强制定义它。目前我有 Move(1);在我的 Update() 方法中被调用只是为了检查移动是否正常(除了我遇到的这个问题)并且它的工作原理是我可以将面板移动到面板,但是由于 CanMove 在更新中被定义为 1函数,动画的事件不会阻止运动。

任何见解将不胜感激!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    你应该稍微改变你的设计。删除canMove 作为传递给Move 的参数,并使其成为玩家类的字段。然后有一个功能来设置canMove。然后有一个单独的函数,如果canMove 为真,则允许您移动。像这样的:

    private bool canMove = true;
    
    public void SetMove(int setCanMove) // called with animation events
    {
        canMove = setCanMove == 1 ? true : false;
    }
    
    public void Move()
    {
        if (Input.GetAxisRaw("Horizontal") == 1 && canMove == true) //go right
        {
            //movement code and animation call...
        }
        // Other directions...
    }
    

    然后您可以使用您的动画事件调用setMove 函数并在它们持续期间停止玩家移动。即在MovingOut 动画的开头调用setMove(false),在MovingIn 动画的结尾调用setMove(true)。这将停止在您的 Update 循环中设置 canMove

    【讨论】:

    • Unity 动画事件不允许您调用带有布尔参数的函数,当您尝试添加函数时,它们不会显示在列表中。根据文档,它只接受“float、string、int、对象引用或 AnimationEvent 对象”,所以不幸的是这似乎不起作用......这就是我将它作为 int 尝试设置的最初原因它是 0 和 1 的整数,而不是布尔值。
    • 啊,我的错,你仍然可以使用这个方法。只需将 canMove 变量更改为 int 并使用 setter 方法将其设置在 1 和 0 之间。
    • @SolAureus 我已经更新了我的答案,以展示你如何做到这一点。如果传递了1,这会将canMove 设置为true,并将任何其他值设置为false。
    【解决方案2】:

    您可以从动画师的GetInteger 函数中获取整数值,该函数将返回设置为当前动画的integer 值。

    if(this.GetComponent<Animator>().GetInteger(canmove)==0)
      //move
    else
      //can't move
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2012-07-27
      • 2015-11-19
      • 2014-03-25
      相关资源
      最近更新 更多