如何在简单的旋转补间中完善角度

时间:2016-05-16 17:31:17

标签: c# unity3d rotation interpolation tween

我正在创建一个协程,它会在一段时间内围绕特定点旋转对象。旋转部分工作正常,唯一的问题是当我尝试设置完美的角度以避免万向节锁定时。

protected bool _isRotating = false;

/// <summary>
/// Rotates the hand around a specific point
/// </summary>
/// <param name="point">The point to rotate around</param>
/// <param name="perspective">
/// The perspective view in which the transform occurs, by default this is Camera.Main
/// </param>
public IEnumerator RotateHand(GameHelper.Axis axis, bool isPositiveDirection, 
                              Vector3 isolatedRotationPoint, float inTime = 1f, 
                              int degrees = GameHelper.RIGHT_ANGLE_DEGREES,
                              Transform perspective = null)
{
    if (_isRotating)
    {
        yield break;
    }

    _isRotating = true;

    var targetPerspective = perspective ?? Camera.main.transform;

    int charge = isPositiveDirection ? 1 : -1;
    int normalizedDegrees = degrees * charge;

    var noralizedAxisVector = this.GetNormalizeHandVectors(axis, targetPerspective);

    var perfectAngles = transform.eulerAngles +(noralizedAxisVector * normalizedDegrees);


    float startTime = Time.time;
    float endTime = startTime + inTime;
    while (Time.time < endTime)
    {
        var delta = normalizedDegrees * (Time.deltaTime / inTime);
        transform.RotateAround(isolatedRotationPoint, noralizedAxisVector, delta);
        yield return null;
    }

    //correct end values for loss in floating point percision
    transform.eulerAngles = perfectedAngles;


    _isRotating = false;
}

这很奇怪,因为有些时候物体完全正确旋转,这应该意味着我有一些标志翻转,或者我的轴已关闭。这是根据您的主要观点对轴进行标准化的功能。

protected Vector3 GetNormalizeHandVectors(GameHelper.Axis axis, Transform perspective)
{
    var forward = perspective.transform.TransformDirection(Vector3.forward);
    forward = forward.normalized;

    switch (axis)
    {
        case GameHelper.Axis.X:
        {
            return perspective.transform.TransformDirection(Vector3.right);
        }
        case GameHelper.Axis.Y:
        {
            return perspective.transform.TransformDirection(Vector3.up);
        }
        case GameHelper.Axis.Z:
        {
            return perspective.transform.TransformDirection(Vector3.forward);   
        }
    }

    throw new Exception("Axis Not Found");
}

有谁知道,我如何设置适当的完美角度?

1 个答案:

答案 0 :(得分:2)

不确定这是否适用于您的情况,但是当使用Quaternions代替XYZ旋转时,也可以解决万向节锁的问题。该类提供角度轴旋转的转换。