Movement in the direction where the camera is looking

Hello! I made the first-view camera. The camera itself is OK. But when I look to the back, the player is moving forward. I’ve spent a lot of hours trying to understand and not just pasting code, so I hope someone will tell me. There are my scripts.

Player:

private void Update()
{
    Movement();
}


private void Movement()
{
    float moveDistance = playerSpeed * Time.deltaTime;
    Vector2 inputVector = gameInput.GetMovementVectorN();

    Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);

    transform.position += moveDir * moveDistance;

} 

Camera:

  void Update()
 {
     Camera();
    
 }

 private void Camera()
 {
     inputVector = gameInput.GetAxisForCamera();
     
     float mouseX = inputVector.x * mouseSensitivity * Time.deltaTime; // Here I made it through new Input system, not Input.GetAxis("")

     float mouseY = inputVector.y * mouseSensitivity * Time.deltaTime;


     cameraVerticalRotation -= inputVector.y;
     cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
     transform.localEulerAngles = Vector3.right * cameraVerticalRotation;


     player.Rotate(Vector3.up * inputVector.x);
 } 

The camera is child object of Player object for now.

I’m not sure, but what about

[SerializeField] private Transform camera;

private void Movement()
{
    float moveDistance = playerSpeed * Time.deltaTime;

    Vector3 moveDir = camera.forward;
    moveDir.y = 0f;

    transform.position += moveDir * moveDistance;

}

Unity - Scripting API: Transform.forward (unity3d.com)

1 Like

Replace line 12 of the player script with this:

Vector3 moveDir = (transform.right*inputVector.x + transform.forward*inputVector.y).normalized;

Also, remove the Time.deltaTime from lines 11 and 13 of the camera script. Mouse movement is frame rate independent.

The answer was close hahaha
Yep. It works. Thank u a lot!