In my scene, there is a player Gameobject with a Character Controller and it contains a first person camera as child. To make the camera stutter less, I tried to use smoothing but there is some strange bug that makes the camera rotation bounce around.
Here is the script for the movement of the Character Controller, which is attached to the player GameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour
{
public CharacterController playerController;
public float moveSpeed;
float hor;
float ver;
Vector3 direction;
void getInput()
{
hor = Input.GetAxisRaw("Horizontal");
ver = Input.GetAxisRaw("Vertical");
}
void Walk()
{
direction = (transform.right * hor + transform.forward * ver) * moveSpeed;
playerController.Move(direction * Time.deltaTime);
}
void Update()
{
getInput();
Walk();
}
}
Here is the script for the first person camera, which is attached to the Camera GameObject. Remember, it’s the child of player GameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPersonCamera : MonoBehaviour
{
public Transform playerTransform;
float mouseX;
float mouseY;
float rotX;
float rotY;
public float mouseRotationSpeed;
float velocity = 0;
private void Start()
{
}
void GetInput()
{
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
rotX += mouseY * mouseRotationSpeed;
rotY += mouseX * mouseRotationSpeed;
rotX = Mathf.Clamp(rotX, -90, 90);
}
void LockCursor()
{
if (Input.GetKey(KeyCode.Escape))
Cursor.lockState = CursorLockMode.None;
else
Cursor.lockState = CursorLockMode.Locked;
}
void RotateY()
{
playerTransform.rotation = Quaternion.Euler(0, Mathf.SmoothDampAngle(playerTransform.eulerAngles.y, rotY, ref velocity, 0.02f), 0);
}
void RotateX()
{
transform.localRotation = Quaternion.Euler(Mathf.SmoothDampAngle(transform.localEulerAngles.x, -rotX, ref velocity, 0.02f), 0, 0);
}
void Update()
{
GetInput();
LockCursor();
}
private void LateUpdate()
{
RotateY();
RotateX();
}
}
When I only run RotateY() or RotateX() in LateUpdate, it works fine. But as soon as I add both, the Camera starts to bug.
Thanks in advance!