- Home /
How to lock z axis rotation
Hi, I am sorry if this has been asked often but I am quite new to unity and have been searching for an answer on this website/google for a while. I have been trying to create a first person player controller that can move and look around. The problem is that when I look around the Z axis rotation value keeps changing when it shouldn't. Because of this the camera is almost always tilted. So my question is how do I lock the Z axis of the rotation if that is the right way to solve it?
public class PlayerMovement : MonoBehaviour { [SerializeField] float movementSpeed = 10f; [SerializeField] float rotationSpeed = 100f; void Start() { Cursor.lockState = CursorLockMode.Locked; } void Update() { transform.Translate(Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime); transform.Rotate(-Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime, Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime, 0); } }
Answer by JonPQ · Dec 18, 2018 at 08:17 PM
try using Transform.RotateAround https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
specify "Vector3.up" (world space up) when rotating left/right as the axis and specify your character's transform.right as the axis for look up/down.
over time you might still get a little titling, so you have to continually correct for this... You can try making sure the Y component of the player transform's right vector is always 0. (read it... set y to 0, re-normalize the vector, then write it back again)
alternatively... use the Camera's " transform.right " as the axis for look up/down rotation.
Answer by Squidicus · May 16, 2020 at 10:58 AM
A simple way you can fix this is to keep the x axis on the player but make a new script for the camera on the y axis
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Problems with code to tilt an object left and right 0 Answers
Having trouble trying to get rotation to work 1 Answer
Multiple Cars not working 1 Answer