【问题标题】:How to rotate an object around itself?如何围绕自身旋转对象?
【发布时间】:2019-07-07 14:02:22
【问题描述】:

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

这是当前状态:

这就是我想要的:

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

    }
}

【问题讨论】:

    标签: c# unity3d rotation quaternions


    【解决方案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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2017-02-10
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多