unity如何将二维物体旋转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 之前停止它。我该怎么做?

enter image description here

创建一个基于 deltaTime 旋转的 coroutine 并跟踪它旋转了多远,一旦达到 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;
    }
}