如何在固定的时间内旋转rigidBody2d?

时间:2016-11-17 11:12:36

标签: animation unity3d rotation rigid-bodies

我是Unity开发的新手。我有一个RigidBody 2D的球,我希望它旋转1秒钟。速度无关紧要。速度可以自动。

我只想:在第二个0位于初始位置,在第二个位置处于最终位置。旋转可以是:180度,360度,720度等等。

我尝试了angularVelocity,但从未停止过。我尝试添加扭矩但相同。我不知道如何处理它。

rb.angularVelocity = 180;

rb.AddTorque(90);

1 个答案:

答案 0 :(得分:1)

如果您想在一定时间后达到精确旋转,则意味着您的旋转速度将自动计算。为了实现这样的目的,我建议使用 Coroutine

public class TestScript : MonoBehaviour
{
    public float targetAngle;
    public float rotationDuration;

    void Update()
    {
        //This is only to test the coroutine
        if(Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(RotateBall(targetAngle, rotationDuration));
        }
    }

    private IEnumerator RotateBall(float a_TargetAngle, float a_Duration)
    {
        Vector3 startLocalEulerAngles = GetComponent<RectTransform>().localEulerAngles;
        Vector3 deltaLocalEulerAngles = new Vector3(0.0f, 0.0f, a_TargetAngle - startLocalEulerAngles.z);
        float timer = 0.0f;

        while(timer < a_Duration)
        {
            timer += Time.deltaTime;
            GetComponent<RectTransform>().localEulerAngles = startLocalEulerAngles + deltaLocalEulerAngles * (timer / a_Duration);
            yield return new WaitForEndOfFrame();
        }

        GetComponent<RectTransform>().localEulerAngles = startLocalEulerAngles + deltaLocalEulerAngles;
    }
}