如何在固定周期内旋转 rigidBody2d?
How to rotate a rigidBody2d in a fixed period?
我是 Unity 开发的新手。我有一个带有 RigidBody 2D
的球,我希望它旋转 1 秒。速度无所谓。速度可以自动。
我只想:在第 0 秒处于初始位置,在第 1 秒处于最终位置。旋转可以是:180、360、720 等度数。
我试过 angularVelocity
但从未停止。我尝试增加扭矩但相同。我不知道怎么办。
rb.angularVelocity = 180;
或
rb.AddTorque(90);
如果你想在一定时间后达到精确的旋转,这意味着你的旋转速度会自动计算。要实现这样的目标,我建议使用 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;
}
}
我是 Unity 开发的新手。我有一个带有 RigidBody 2D
的球,我希望它旋转 1 秒。速度无所谓。速度可以自动。
我只想:在第 0 秒处于初始位置,在第 1 秒处于最终位置。旋转可以是:180、360、720 等度数。
我试过 angularVelocity
但从未停止。我尝试增加扭矩但相同。我不知道怎么办。
rb.angularVelocity = 180;
或
rb.AddTorque(90);
如果你想在一定时间后达到精确的旋转,这意味着你的旋转速度会自动计算。要实现这样的目标,我建议使用 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;
}
}