如何让动画在Unity中等待另一个动画

时间:2017-10-01 14:51:55

标签: c# .net animation unity3d animator

我是团结的新手,我刚开始学习动画和动画师。我正在做一个简单的游戏,玩家可以走路(并且当时正在播放动画)或击中(当时正在播放攻击动画)它也可以跳跃(跳过动画播放)。否则播放器处于空闲状态(空闲动画播放)。问题是,当我试图击中时,它没有击中(它已经看到动画师开始播放命中动画,但随后开始空闲动画)。我的观点是,在渲染一帧之后,会调用另一个更新,因此即使攻击尚未结束,也会播放空闲动画。我的代码如下所示:

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

public class KnightController : MonoBehaviour {

    private Rigidbody2D _rigidBody;
    private Animator _animator;
    private bool _isGrounded;
    private bool _isJumped;
    private bool _isAttacking;

    void Start () {
        _rigidBody = GetComponent<Rigidbody2D>();
        _animator = GetComponent<Animator>();
        _isGrounded = true;
        _isJumped = false;
        _isAttacking = false;
    }

    // Update is called once per frame
    void Update () {
        float walkSpeed = Input.GetAxis("Horizontal");

        if (Mathf.Abs(walkSpeed) > float.Epsilon && _isGrounded)
        {
            Vector2 oldVelocity = _rigidBody.velocity;
            _rigidBody.velocity = new Vector2(walkSpeed * 3, oldVelocity.y);
            transform.localScale = new Vector2(Mathf.Sign(walkSpeed), transform.localScale.y);
            _animator.Play("KnightWalk");
        }

        if (Input.GetKey(KeyCode.W))
        {
            _isJumped = true;
        }

        if (Mathf.Abs(walkSpeed) <= float.Epsilon && _isGrounded && !_isAttacking)
        {
           // _animator.Play("KnightIdle");
        }

        if (Input.GetMouseButtonDown(0))
        {
            _animator.Play("KnighAttack");
        }
    }
    private void FixedUpdate()
    {
        if (_isJumped)
        {
            if (_isGrounded)
            {
                _rigidBody.AddForce(new Vector2(0, 160));
                _animator.Play("KnightJump");
            }
            _isJumped = false;
        }
    }
    private void OnCollisionStay2D(Collision2D collision)
    {
        _isGrounded = true;
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        _isGrounded = false;
    }
}

有关如何修复它的任何建议?如果我做错了什么,请不要犹豫。

1 个答案:

答案 0 :(得分:1)

是的,你做错了。您的假设是正确的,您正在使用Animator.Play()方法强制播放动画。您应该使用动画控制器的状态,条件和转换。看看这个:https://docs.unity3d.com/Manual/class-AnimatorController.html