uRThow
uRThow

Reputation: 27

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. This happens because the Z and X axis ofcourse rotate with the Y axis I manipulated earlier when rotating it left or right.

I made two gifs showcasing the problem:

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. Thanks in advance!

Update:

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

Upvotes: 0

Views: 2476

Answers (1)

Chris H
Chris H

Reputation: 972

Try using Transform.RotateAround instead localEulerAngles.

Upvotes: 3

Related Questions