如何围绕自身旋转对象?

时间:2019-07-07 14:02:22

标签: c# unity3d rotation quaternions

我想在Unity3D中旋转一个立方体,当我按下键盘上的向左箭头按钮时,立方体必须向左旋转。如果我向上推,则立方体必须向上旋转。但是在我的脚本中,立方体向左旋转,然后左侧向上旋转。

这是当前状态:

enter image description here

这就是我想要的:

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotate : MonoBehaviour
{
    public float smooth = 1f;
    private Quaternion targetRotation;
    // Start is called before the first frame update
    void Start()
    {
        targetRotation = transform.rotation;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.UpArrow)){
            targetRotation *= Quaternion.AngleAxis(90, Vector3.right);
        }
        if(Input.GetKeyDown(KeyCode.DownArrow)){
            targetRotation *= Quaternion.AngleAxis(90, Vector3.left);
        }
        if(Input.GetKeyDown(KeyCode.LeftArrow)){
            targetRotation *= Quaternion.AngleAxis(90, Vector3.up);
        }
        if(Input.GetKeyDown(KeyCode.RightArrow)){
            targetRotation *= Quaternion.AngleAxis(90, Vector3.down);
        }
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10* smooth * Time.deltaTime);

    }
}

1 个答案:

答案 0 :(得分:1)

您需要交换四元数乘法的顺序。

您现在拥有的方式是,将旋转应用于原始旋转后的轴,因为您实际上在做targetRotation = targetRotation * ...;

但是,您想绕世界轴旋转旋转。您可以执行targetRotation = ... * targetRotation;

void Update()
{
    if(Input.GetKeyDown(KeyCode.UpArrow)){
        targetRotation = Quaternion.AngleAxis(90, Vector3.right) * targetRotation;
    }
    if(Input.GetKeyDown(KeyCode.DownArrow)){
        targetRotation = Quaternion.AngleAxis(90, Vector3.left) * targetRotation;
    }
    if(Input.GetKeyDown(KeyCode.LeftArrow)){
        targetRotation = Quaternion.AngleAxis(90, Vector3.up) * targetRotation;
    }
    if(Input.GetKeyDown(KeyCode.RightArrow)){
        targetRotation = Quaternion.AngleAxis(90, Vector3.down) * targetRotation;
    }
    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10* smooth * Time.deltaTime);

}

有关更多信息,请参见How do I rotate a Quaternion with 2nd Quaternion on its local or world axes without using transform.Rotate?

相关问题