[英]How to rotate a 2D object by 90 degrees in unity
我需要將 2D GameObject
z 軸旋轉 90 度。 所以我已經嘗試過transform.RotateAround
但仍然旋轉了一個完整的圓圈:
transform.RotateAround(target.transform.position, new Vector3 (0, 0, -90),
50f * Time.deltaTime)
我需要在 90 之前停止它。我該怎么做?
創建一個基於deltaTime
旋轉的協同程序,並跟蹤它旋轉了多遠,一旦達到90
就停止。 使用Mathf.Min
確保不要旋轉超過 90。
private isRotating = false;
// speed & amount must be positive, change axis to control direction
IEnumerator DoRotation(float speed, float amount, Vector3 axis)
{
isRotating = true;
float rot = 0f;
while (rot < amount)
{
yield return null;
float delta = Mathf.Min(speed * Time.deltaTime, amount - rot);
transform.RotateAround(target.transform.position, axis, delta);
rot += delta;
}
isRotating = false;
}
然后當你想開始旋轉時,啟動協程(如果它還沒有旋轉):
if (!isRotating)
{
StartCoroutine(DoRotation(50f, 90f, Vector3.back));
}
保存協程本身而不是使用標志稍微好一些。 這可以讓你做一些事情,比如在任何時候停止旋轉。
private Coroutine rotatingCoro;
// speed & amount must be positive, change axis to control direction
IEnumerator DoRotation(float speed, float amount, Vector3 axis)
{
float rot = 0f;
while (rot < amount)
{
yield return null;
float delta = Mathf.Min(speed * Time.deltaTime, amount - rot);
transform.RotateAround(target.transform.position, axis, delta);
rot += delta;
}
rotatingCoro = null;
}
// ...
if (rotatingCoro != null)
{
rotatingCoro = StartCoroutine(DoRotation(50f, 90f, Vector3.back));
}
// ...
// call to stop rotating immediately
void StopRotating()
{
if (rotatingCoro != null)
{
StopCoroutine(rotatingCoro);
rotatingCoro = null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.