问题描述
因此,我正在编写一个脚本,该脚本能够使用鼠标移动来旋转对象.我设置的场景是一个照相机,前面有一个物体.向左移动鼠标会导致对象向左旋转,向上移动鼠标会导致对象向上旋转,依此类推.现在,我有一个小问题.当我将对象向左或向右旋转90度,然后向上或向下旋转时,它绕Z轴而不是X轴旋转,就像我想要的那样.发生这种情况的原因是,当向左或向右旋转时,课程的Z和X轴随我之前操纵的Y轴一起旋转.
So I'm writing a script that's able to rotate an object using mouse movements.The scene I have set up is a camera with an object in front of it. Moving the mouse left results in the object rotating left, moving the mouse up results in the object rotating up, etc. Now I have a little problem. When I rotate the object 90 degrees left or right and then rotate it up or down it rotates around the Z axis instead of the X axis like I want it to. This happens because the Z and X axis ofcourse rotate with the Y axis I manipulated earlier when rotating it left or right.
我制作了两个展示问题的GIF:
I made two gifs showcasing the problem:
实际发生的情况: https://media.giphy.com/media/1jl3MNtMuXW9AAUQOZ/giphy.gif
这是我当前正在使用的代码:
Here's the code I'm currently using:
public float object_rotSens = 100.0f;
float object_rotY = 0.0f;
float object_rotX = 0.0f;
void Update()
{
object_rotX += Input.GetAxis("Mouse X") * object_rotSens * Time.deltaTime;
object_rotY += Input.GetAxis("Mouse Y") * object_rotSens * Time.deltaTime;
objectImRotating.transform.localEulerAngles = new Vector3(object_rotY, -object_rotX, 0);
}
我希望有人可以帮助我更改代码,这样即使对象绕Y轴旋转了任意角度,我也拥有了首选的旋转方式.预先感谢!
I hope that someone can help me change the code so I have the preferred rotation even when the object is rotated any amount around the Y axis. Thanks in advance!
更新:
Chris H帮助我解决了这个问题.对于任何有相同问题的人,这是帮助我解决问题的原因:
Chris H helped me fix the problem. For anyone who has the same problem here's what helped me fix the problem:
object_rotX = Input.GetAxis("Mouse X") * object_rotSens * Time.deltaTime;
object_rotY = Input.GetAxis("Mouse Y") * object_rotSens * Time.deltaTime;
objectImRotating.transform.RotateAround(objectImRotating.transform.position, new Vector3(object_rotY, -object_rotX, 0), 100 * Time.deltaTime);
推荐答案
尝试使用转换.RotateAround 而不是localEulerAngles.
Try using Transform.RotateAround instead localEulerAngles.
这篇关于Unity对象未围绕正确的轴旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!