Hey there, I am trying to implement a 3D character controller for an FPS game, and wanted to add a slight tilt to the camera when strafing left or right. Doing some research, I found this code:
void Update()
{
float z = Input.GetAxis("Horizontal") * -15.0f; // might be negative, just test it
Vector3 euler = transform.localEulerAngles;
euler.z = Mathf.Lerp(euler.z, z, 2.0f * Time.deltaTime);
transform.localEulerAngles = euler;
}
When I try implementing it, here’s how it looks:
As you can see, when tilting to the left everything works fine. When tilting to the right, however, the character performs a somersault like motion. I tried this on a blank unity project on just a cube and the same exact behavior occured, meaning it’s not something with another script.
Someone told me that it has to do with Lerping euler angles, since negative angles and positive angles can equal eachother, but I had a few questions: For one, how do I get around this? They mentioned just using Rotate, but I want a really smooth Lerp motion not just a fixed motion. Second of all, can I modify Quaternions directly, bypassing euler angles? And third, why would this only apply to the right motion and not the left? I understand that right motion in this case means a negative Z rotation, and negative angles can equal positive angles. But then, can’t positive angles also equal negative angles? Regardless, that’s moreso for curiosity’s sake, the other two questions are more important.
Peace and Love
EDIT: Found my own solution, but going to keep it up 1. So others in the same position can find the issue, but also because the original question still stands. This method doesn’t use Lerp.
float horizontalInput = Input.GetAxis("Horizontal") * -5f;
if(transform.rotation.z >= -5 || transform.rotation.z <= 5)
{
transform.localRotation = Quaternion.Euler(0f, 0f, horizontalInput);
}
EDIT 2: So, my previous solution is actually really choppy when moving from a right tilt to a left tilt or vice-versa. Another commenter has a great solution!