Unity2D如何使Ai运行随机方向

时间:2018-09-23 08:32:38

标签: unity3d

YouTube中有一些教程,但是为什么呢? 是的,ai确实会在随机方向上运行,但动画却不会。甚至AI都将其静止的动画移动了。有人是否有源代码或想法可以使它按应有的方式工作?请帮我即时停留在这个东西上一个星期。 我已经尽了一切努力,但一切都失败了,请帮助我,求求您。我只有1天的时间才能完成为我们学校期中考试创建的基本游戏。我不想失败T_T

    public float moveSpeed;
    private Rigidbody2D myRigidbody;

    public bool isWalking;

    public float walkTime;
    private float walkCounter;
    public float waitTime;
    private float waitCounter;
    private int walkDirection;


    public Animator animator;

    void Start()
    {

         animator = GetComponent<Animator>();
         animator.SetBool("IsRunning", true);

        myRigidbody = GetComponent<Rigidbody2D>();
        waitCounter = waitTime;
        walkCounter = walkTime;
        ChooseDirection();

    }

    void Update()
    {
        animator.SetBool("IsRunning", isWalking);
        if (isWalking)
        {
            walkCounter -= Time.deltaTime;

            switch (walkDirection)
            {
                case 0:
                    myRigidbody.velocity = new Vector2(0, moveSpeed);
                    break;
                case 1:
                    myRigidbody.velocity = new Vector2(moveSpeed, 0);
                    break;
                case 2:
                    myRigidbody.velocity = new Vector2(0, -moveSpeed);
                    break;
                case 3:
                    myRigidbody.velocity = new Vector2(-moveSpeed, 0);
                    break;
            }
            if (walkCounter < 0)
            {
                isWalking = false;
                waitCounter = waitTime;
            }
        }
        else
        {
            waitCounter -= Time.deltaTime;
            myRigidbody.velocity = Vector2.zero;
            if (waitCounter < 0)
            {
                ChooseDirection();
            }
        }
    }
    public void ChooseDirection()
    {

        walkDirection = Random.Range(0, 4);
        isWalking = true;
        walkCounter = walkTime;
    }
}

1 个答案:

答案 0 :(得分:2)

在“开始”上获取动画师参考

public Animator animator;
void Start()
{
     //Assuming that the Animator is attached to the same Game Object as this script
     animator = GetComponent<Animator>();
}

创建一个参数(在本例中为一个名为“ IsRunning”的布尔值),并在开始运行时进行设置

animator.SetBool("IsRunning", true);

在您的情况下,您可能希望随着“ isWalking”变量的更改来更新状态,因此在Update上进行

animator.SetBool("IsRunning", isWalking);