I have a simple scene with a player in it. The player is a Capsule with a rigidbody and holds all scripts concerning movement, Camera movement, etc. The player-GameObject is also the parent of a Camera- GameObject, which I use for the first person perspective. The problem is the following: When I move the rigidbody of the player using force, the camera stutters. The movement loop of the player is run in FixedUpdate and the Camera movement loop is run in LateUpdate.
Here is the script for the movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour
{
public Rigidbody playerRigidb;
public Camera firstPersonCam;
public float moveSpeed;
float hor;
float ver;
void getInput()
{
hor = Input.GetAxisRaw("Horizontal");
ver = Input.GetAxisRaw("Vertical");
}
void Walk()
{
playerRigidb.AddForce(transform.forward * ver + transform.right * hor, ForceMode.VelocityChange);
}
void Update()
{
getInput();
}
private void FixedUpdate()
{
Walk();
}
}
And here is the script to move the Camera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPersonCamera : MonoBehaviour
{
public Rigidbody playerRigidb;
public Camera firstPersonCam;
float mouseX;
float mouseY;
float rotX;
float rotY;
public float mouseRotationSpeed;
// Start is called before the first frame update
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;
}
// Update is called once per frame
void Update()
{
GetInput();
LockCursor();
}
private void LateUpdate()
{
firstPersonCam.transform.localRotation = Quaternion.Euler(-rotX, 0, 0);
transform.rotation = Quaternion.Euler(0, rotY, 0);
}
}
I already tried:
- Using different types of “Update”
- Interpolation in rigidbody
- Removing the Camera as child of the player
And I also tried searching for other answers on the internet, but nothing helped me.
Thank you in advance!