我想在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);
}
}
答案 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);
}