Character bounces when walking and looking up/down.

Hello everyone,

I’m sorry if I’m asking a question that was asked plenty of times in the past, I’ve been looking for an answer for a while now and I’ve tried countless different things.

I’m learning Unity at the moment and have made the following script:

public class CameraPlayerMove : MonoBehaviour
{
    public Vector2 turn;
    public float sensitivity = 2;
    public float verticalInput;
    public float moveSpeed = 20;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        turn.x += Input.GetAxis("Mouse X") * sensitivity;
        turn.y += Input.GetAxis("Mouse Y") * sensitivity;
        transform.localRotation = Quaternion.Euler(-turn.y, turn.x, 0);

        verticalInput = Input.GetAxis("Vertical");
        transform.Translate(Vector3.forward * verticalInput * moveSpeed * Time.deltaTime);
    }
}

The script is applied to the Main Camera. I give it a rigidbody and capsule collider.
I lock all rotation in the rigidbody constraints and set the mass to 80.

I get a nice working way of walking with W and S while moving the mouse to controll side to side and up and down movement.

However, when I look up or down and try to walk forward or backward, my camera gets bounced up. It eventually lands, even if I hold the W/S key to keep moving.

I am positive this is something basic that I am overlooking, but I cannot seem to find anything regarding this, probably because I have issues to phrase this issue in order to look it up.

EDIT1:
I’ve added the following condition before the transform.Translate method in order to check whether the player is on the ground when allowing him to walk, but the same happens.

if(Physics.Raycast(transform.position, -Vector3.up, GetComponent<Collider>().bounds.extents.y + 0.1f))

Anyways, thank you in advance,
Matt

A common control scheme for a first-/third-person, mouse-aimed system involves separating horizontal and vertical movement between the character and the camera respectively.

As it stands right now, your character falls onto their face to look down and falls onto their back to look up. Then, when you apply movement using Transform.Translate(), you’re propelling the character in that same direction, bouncing them off the ground or flying into the air.


Basically, what you're looking for would be along the lines of:
playerTransform.rotation = Quaternion.Euler(0f, turn.x, 0f);
cameraTransform.rotation = Quaternion.Euler(-turn.y, 0f, 0f);

(It’s a little more work than just that, but that’s the gist of it)