Hello. I’m making a game and ran into a problem from the very beginning. I started creating an FPS Controller, but various problems cropped up for me.
- Sometimes camera glitches appear in the build and editor, although the scene is relatively empty and cannot load anything. Probably the problem lies in the code.
- For some reason, when the camera rotation approaches an angle of 0 degrees along the X axis, it rotates faster than at 90 and -90 degrees.
Please help, it’s very frustrating that errors appear from the very beginning.
I will be very glad for advice on the code.
Thank you.
using System.Threading;
using UnityEngine;
using UnityEngine.Rendering;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float _movementSpeed;
[SerializeField] private Transform _camera;
[SerializeField] private float _mouseSensitivity;
private CharacterController _characterController;
private float _factor = 1f;
private float _gravity = 0f;
private float xRotation = 0f;
private float yRotation = 0f;
private void Start()
{
_characterController = GetComponent<CharacterController>();
}
private void Update()
{
HandleMovement();
HandleCameraRotation();
}
private void HandleMovement()
{
float hor = Input.GetAxisRaw("Horizontal");
float ver = Input.GetAxisRaw("Vertical");
if (ver < 0f)
_factor = 0.5f;
else if (Input.GetKey(KeyCode.LeftShift))
_factor = 1.5f;
else
_factor = 1f;
if (_characterController.isGrounded)
_gravity = -2f;
else
_gravity -= 9.81f * Time.deltaTime;
Vector3 move = transform.forward * ver + transform.up * _gravity + transform.right * hor;
_characterController.Move(move * _movementSpeed * _factor * Time.deltaTime);
}
private void HandleCameraRotation()
{
float mouseX = Input.GetAxis("Mouse X") * _mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * _mouseSensitivity * Time.deltaTime;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
_camera.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
transform.rotation = Quaternion.Euler(Vector3.up * yRotation);
}
}
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
[SerializeField] private Transform _playerHead;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
transform.position = _playerHead.position;
}
}


