mouse look problem

I made a c# mouse look script but when i look up my player walks backward by himself and when i look down my player walks forward here is the script:

using System;
using UnityEngine;

public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

void Start ()
{
	Vector3 rot = transform.localRotation.eulerAngles;
	rotY = rot.y;
	rotX = rot.x;
}

void Update ()
{
	float mouseX = Input.GetAxis("Mouse X");
	float mouseY = -Input.GetAxis("Mouse Y");

	rotY += mouseX * mouseSensitivity * Time.deltaTime;
	rotX += mouseY * mouseSensitivity * Time.deltaTime;

	rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

	Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
	transform.rotation = localRotation;
}

}

The problem isn’t exactly that you’re “walking” forward or backward.

You’re almost definitely using a capsule (and/or collider) for your first-person character. The problem you’re experiencing is due to how the physics engine interacts with your script.

Look at it this way: If you have a capsule and stand it perfectly upright, it won’t tip in any direction. Once it does lean, it falls over, throwing its weight toward the ground in the direction it topples.

However, rather than falling over, your capsule is in a constant state of leaning, trying to fall over. During every physics pass, the capsule thinks it’s supposed to be tipping over, but you’re constantly correcting for that rotation. Instead, it looks like it’s sliding around. Essentially, it’s falling forever on flat ground.


So how can this be dealt with?

Well, the problem occurs when you lean forward and backward. There’s no problem with left and right because the capsule would still be standing upright on its end.

Therefore, an accommodation needs to be made for looking up and down. Rather than rotating the character on that axis, rotate the camera itself:

playerRotation = Quaternion.Euler(0.0f, rotY, 0.0f);
cameraRotation = Quaternion.Euler(rotX, 0.0f, 0.0f);
transform.rotation = playerRotation;
playerCamera.transform.rotation = cameraRotation;