夹紧四元数旋转会导致抖动

时间:2016-03-04 18:55:55

标签: c# unity3d

我正在使用unity3D游戏引擎。我有一个玩家,它是一个立方体,附有一个刚体。重力关闭,角度拖动设置为0.我正在旋转它使用AddTorque,但我想确保x角度永远不会超过rotationClampLow(当前为45度)并且永远不会低于rotationClampHigh(目前为315)度)。所以x角可以是除了大于45或小于315之外的任何值。

这是我目前的代码:

 // rotationSpeed is a float currently set at 3.
 void RotatePlayer () {
    horizontalRotation = rotationSpeed * Input.GetAxisRaw("HorizontalRotate");
    verticalRotation = rotationSpeed * Input.GetAxisRaw("VerticalRotate");

    if ( horizontalRotation != 0 )
        Debug.Log("Horizontal rotation input: " + horizontalRotation);

    ClampPlayerRotation();

    rb.angularVelocity = Vector3.zero;
    rb.AddTorque(horizontalRotation, verticalRotation, 0f, ForceMode.VelocityChange);
}


void ClampPlayerRotation () {

    // I use 180 because it is halfway between 45 and 315
    if ( rb.rotation.eulerAngles.x >= rotationClampLow && rb.rotation.eulerAngles.x <= 180) {

        // Make sure that the x rotation isn't more than the low clamp
        transform.eulerAngles = new Vector3(rotationClampLow, rb.rotation.eulerAngles.y, rb.rotation.eulerAngles.z);

        //Make sure no positive torque is added to the x axis
        if ( horizontalRotation > 0 )
            horizontalRotation = 0;
    }
    else if ( rb.rotation.eulerAngles.x <= rotationClampHigh && rb.rotation.eulerAngles.x > 180 ) {

        // Make sure that the x rotation isn't less than the high clamp
        transform.eulerAngles = new Vector3(rotationClampHigh, rb.rotation.eulerAngles.y, rb.rotation.eulerAngles.z);

        //Make sure no negative torque is added to the x axis
        if ( horizontalRotation < 0 )
            horizontalRotation = 0;
    }

当x旋转达到45时,立方体停止旋转,但当它达到315时,它开始在310到315度之间抖动。如何解决这个问题?任何帮助将不胜感激。

修改:Here is what is happening

编辑2:正在从FixedUpdate()调用RotatePlayer()。

编辑3:更改了以下代码:

rb.rotation = Quaternion.Euler(new Vector3(rotationClampLow, rb.rotation.eulerAngles.y, rb.rotation.eulerAngles.z));

要:

transform.eulerAngles = new Vector3(rotationClampLow, rb.rotation.eulerAngles.y, rb.rotation.eulerAngles.z);

0 个答案:

没有答案