So I have an empty object called player with the PlayerMovement script and a rigidbody. I have the main camera and player visual as childs of it. The movement works fine as long as I freeze the rigidbody's x and z rotation, but why is that? Here is my player code (minus a couple of things that would just make it harder for you to help me):
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { [SerializeField] private float speed = 5f; private float xLook; private float yLook; [SerializeField] private float _mouseSensitivity; [SerializeField] private float _upAndDownMax; [SerializeField] private Rigidbody rb; private Camera _camera; private Vector3 movement; void Start() { rb = GetComponent<Rigidbody>(); _camera = Camera.main; } void Update() { HandleMoveInput(); HandleLookInput(); } private void HandleMoveInput() { float hor = Input.GetAxisRaw("Horizontal"); float ver = Input.GetAxisRaw("Vertical"); Vector3 moveInput = new Vector3(hor, 0, ver); moveInput = transform.forward * moveInput.z + transform.right * moveInput.x; moveInput.Normalize(); movement = moveInput * speed; } private void HandleLookInput() { xLook += Input.GetAxis("Mouse X") * _mouseSensitivity * Time.deltaTime; // transform.rotation = Quaternion.Euler(0, xLook, 0); rb.MoveRotation(Quaternion.Euler(0, xLook, 0)); yLook -= Input.GetAxis("Mouse Y") * _mouseSensitivity * Time.deltaTime; yLook = Mathf.Clamp(yLook, -_upAndDownMax, _upAndDownMax); _camera.transform.localRotation = Quaternion.Euler(yLook, 0, 0); } void FixedUpdate() { MovePlayer(); // LookPlayer(); } private void MovePlayer() { Vector3 currentVelocity = rb.velocity; Vector3 targetVelocity = new Vector3(movement.x, currentVelocity.y, movement.z); Vector3 force = targetVelocity - currentVelocity; force.y = 0; rb.AddForce(force, ForceMode.VelocityChange); } } So I am guessing the problem is inside HandleMoveInput but I am not sure. I am just wondering why I have to freeze the rotation of z and x to make it work.
The second problem is that the camera sometimes start to stutter when colliding with things. I tested and I believe its because of the freeze problem and that its a child of the player. Because it does not happen when its not a child. Is it a bad idea to make the camera I child of the player?
