如何围绕自身旋转物体?

How to rotate an object around itself?

我想旋转立方体 Unity3D.When 我按下键盘上的左箭头按钮立方体必须旋转 left.If 我向上推立方体必须旋转 up.But编写立方体向左旋转然后左侧向上旋转的脚本。

这是当前状态:

这就是我想要的:

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);

    }
}

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

按照您现在的方式,旋转将应用到轴上,就像它们在原始旋转之后一样,因为您正在有效地做 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);

}

有关详细信息,请参阅