簡體   English   中英

如何統一旋轉 2D object 90 度

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM