将物体平滑旋转90度

时间:2020-08-19 08:47:33

标签: c# unity3d

上帝早晨!我想在if语句中将对象平滑旋转90度。我到处都在寻找解决方案,但是找不到适合我的解决方案。这就是我想要的样子:

if (Swipe.Left)
{ 
    Object smooth rotate 90 degrees down //left
}

我希望有人知道我该怎么做!感谢您的帮助:)

编辑:我之前曾尝试过此方法,但似乎不适用于if语句:

Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.down);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, .03f);

3 个答案:

答案 0 :(得分:1)

由于Swipe.Left仅在一帧内返回true,因此您必须将逻辑维持更长的时间。为此,让我们在滑动时启用一个标记,并在达到目标旋转时禁用该标记。

if (Swipe.Left)
{ 
     swiped = true;
     newRotation = Quaternion.AngleAxis(90, Vector3.down);
     slerpEase = .03f;
}

if (swiped)
{ 
    transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, slerpEase);
    slerpEase *= 0.95f;
    if (Mathf.Approximately(1f, Quaternion.Dot(transform.rotation, newRotation)))
        swiped = false; // reached the target rotation
}

还要注意,当对象随时间旋转时,我使用了一个名为slerpEase的变量来平稳地减慢旋转速度。您可能需要更改0.95f使其取决于增量时间。

请注意,如果将其绕两个轴旋转,由于云台锁定,比较角度会有些棘手。

答案 1 :(得分:1)

为此,我将使用协程,并使用AnimationCurve确定转弯的平滑度。这样一来,您就可以仅使用检查器来微调所需的外观,并且如果需要不同的程度,还可以很好地重用代码。

[SerializeField] private AnimationCurve swipeRotateAnimationCurve; // configure in inspector
private Coroutine swipeRotateCoroutine = null;
private float swipeRotationDuration = 2f; // duration of rotation in seconds

// ...

if (Swipe.Left)
{ 
    // Cancel any currently running coroutine
    if (swipeRotateCoroutine != null) 
    {
        StopCoroutine(swipeRotateCoroutine);
        swipeRotateCoroutine = null;
    }

    swipeRotateCoroutine = StartCoroutine(DoHorizontalSwipeRotate(-90f));
}
else if (Swipe.Right)
{ 
    // Cancel any currently running coroutine
    if (swipeRotateCoroutine != null) 
    {
        StopCoroutine(swipeRotateCoroutine);
        swipeRotateCoroutine = null;
    }

    swipeRotateCoroutine = StartCoroutine(DoHorizontalSwipeRotate(90f));  
}

// ...

private IEnumerator DoHorizontalSwipeRotate(float degreesRight)
{
    float t = 0;
    Quaternion startRot = transform.rotation;

    // update rotation until 
    while (t < 1f)
    {
        // let next frame occur
        yield return null;

        // update timer
        t = Mathf.Min(1f, t + Time.deltaTime/swipeRotationDuration); 
       
        // Find how much rotation corresponds to time at t:
        float degrees = degreesRight * swipeRotateAnimationCurve.Evaluate(t);

        // Apply that amount of rotation to the starting rotation:
        transform.rotation = startRot * Quaternion.Euler(0f, degrees, 0f);
    }

    // allow for next swipe
    swipeRotateCoroutine = null;
}

答案 2 :(得分:0)

因此,关于Unity中的方向,并不总是我们认为应该的,我已经回答了与此here.相关的问题,因此在您的情况下,顺时针旋转对象,您需要使用Vector3.forward而不是Vector3.down。这涵盖了围绕对象要旋转的巫婆定义一条轴。

现在让我们讨论一下rotate to right / rotate to leftclockwise / counter Clockwise之类的方向。当您想顺时针旋转对象时,可以使用-ve(虚构)角度;当您想逆时针旋转对象时,可以使用+ ve(正)角度。

因此,您的代码应如下所示以顺时针旋转对象:

Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, 0.03f);