为什么角色从不旋转?

时间:2018-12-14 23:26:49

标签: c# unity3d

我希望它们分别从另一侧缓慢旋转180度。 第一个从左向右旋转,第二个从右向左旋转。

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

public class AnimatorController : MonoBehaviour
{
    public Animator[] animators;
    public Transform target;
    public float speed = 1f;
    public float rotationSpeed;

    // Use this for initialization
    void Start()
    {
        for (int i = 0; i < animators.Length; i++)
        {
            animators[i].SetFloat("Walking Speed", speed);
        }
    }

    // Update is called once per frame
    void Update()
    {
        float distanceFromTarget = Vector3.Distance(animators[2].transform.position, target.position);
        if (distanceFromTarget < 15)
        {
            float speed = (distanceFromTarget / 15) / 1;
            for (int i = 0; i < animators.Length; i++)
            {
                animators[i].SetFloat("Walking Speed", speed);
            }
        }

        if (distanceFromTarget < 2f)
        {
            for (int i = 0; i < animators.Length; i++)
            {
                animators[i].SetFloat("Walking Speed", 0);
            }

            animators[0].transform.rotation = Quaternion.RotateTowards(animators[0].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);
            animators[1].transform.rotation = Quaternion.RotateTowards(animators[1].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);
        }
    }
}

到达这两行,但什么也没做:

animators[0].transform.rotation = Quaternion.RotateTowards(animators[0].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);
animators[1].transform.rotation = Quaternion.RotateTowards(animators[1].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);

我还尝试了Quaternion.Slerp上的Quaternion.RotateTowards,但它也没有旋转它们。

1 个答案:

答案 0 :(得分:2)

要使它们朝不同的方向移动,请将它们稍微偏离180度,以使其最接近的方向相反:

if (distanceFromTarget < 2f)
{

    // If they haven't yet rotated, start them rotating in different directions
    if (animators[0].transform.eulerAngles.y == 180f) { 
        float epsilon = 0.001f;
        animators[0].transform.rotation = Quaternion.Euler(0f, 180f - epsilon, 0f);
        animators[1].transform.rotation = Quaternion.Euler(0f, 180f + epsilon, 0f);
    }

    for (int i = 0; i < animators.Length; i++)
    {
        animators[i].SetFloat("Walking Speed", 0);
    }

    animators[0].transform.rotation = Quaternion.RotateTowards(animators[0].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);
    animators[1].transform.rotation = Quaternion.RotateTowards(animators[1].transform.rotation, Quaternion.Euler(0, 180, 0), Time.deltaTime * rotationSpeed);
}