Hi, I was wondering if it is possible to use quaternions for mouse movements, specifically the Y axis, rather than eulerangles? I was wondering if this is possible because eulerangles causes issues with some of the mechanics for my game.
Try this:
-
“mouseInputX” should be your mouse’s
X movement. -
“sensitivty” sets how much the
movement of the mouse affects the
rotation. -
“Time.deltaTime” can be replaced with
“Time.smoothDeltaTime” for a smoother
effect.using UnityEngine; public class MouseRotate: MonoBehaviour { public float MouseInputX; private float sensitivity = 10.0f; void Update() { transform.rotation = Quaternion.AngleAxis(MouseInputX * sensitivity * Time.deltaTime, Vector3.up); } }
Hope that helps!
Yeah you should use a Quaternion for gameObject’s rotation ( this case a camera ).
using UnityEngine;
public class CameraRot : Monobehaviour
{
void Update()
{
transform.rotation = Quaternion(X,Y,Z,W)
}
}
Of course you will edit the “X,Y,Z,W” letters for their Respective coordinates, or you could replace all of the “Quaternion ( )” thing with a variable, but of course that variable will need the Quaternion
Well, you didn’t specify your actual requirement how your input should work. Here i made a mouse look / orbit script which is purely based on quaternions. The rotations never suffer from any gimbal lock or strange flipping due to world axis bounding. However it really let’s you rotate freely around the object which means you can end up in any orientation (great for space simulations).
If you want it to be bound to world axes you kind of have to use eulerangles in some way. Otherwise if you only use relative rotations you might slowly get “errors” in the sense of rotation around an axis you don’t want.
For example if you replace this line:
r = Quaternion.AngleAxis(Input.GetAxis("Mouse X"), transform.up) * r;
with
r = Quaternion.AngleAxis(Input.GetAxis("Mouse X"), Vector3.up) * r;
You rotate around world up axis and around local x axis. So in theory you can’t rotate around z that way. Though due to floating point precision problems after rotating a bit you might notice a slight tilt around z.
So if your rotations should be aligned with world axes you might want to use absolute angles.
float polar = 0;
float elevation = 0;
// LateUpdate
polar += Input.GetAxis("Mouse X");
elevation -= Input.GetAxis("Mouse Y");
r = Quaternion.AngleAxis(elevation, Vector3.right);
r = Quaternion.AngleAxis(polar, Vector3.up) * r;
In this case the absolute rotation is created from distinct angles. Keep in mind if your elevation goes past ± 90° the y rotation seem to be inverted since you’re actually upside down. You still rotate in the same direction but you see it inverted. (Like if you drive an RC car towards you then left / right seems to be inverted).