简体   繁体   English

Unity对象未围绕正确的轴旋转

[英]Unity object not rotating around correct axis

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. 当我将对象向左或向右旋转90度,然后向上或向下旋转时,它绕Z轴而不是X轴旋转,就像我想要的那样。 This happens because the Z and X axis ofcourse rotate with the Y axis I manipulated earlier when rotating it left or right. 发生这种情况的原因是,当向左或向右旋转时,路线的Z和X轴随我之前操纵的Y轴一起旋转。

I made two gifs showcasing the problem: 我制作了两个展示问题的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);
}

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. 我希望有人可以帮助我更改代码,这样即使对象绕Y轴旋转了任意角度,我也可以进行首选旋转。 Thanks in advance! 提前致谢!

Update: 更新:

Chris H helped me fix the problem. 克里斯·H(Chris H)帮助我解决了问题。 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);

尝试使用Transform.RotateAround而不是localEulerAngles。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM