How to convert Input.GetAxis(“Mouse X”) or Input.GetAxis(“Mouse Y”) to the new Input System?

I’m new on Unity Scripting, and I’m trying to make a ThirdPersonCamera, so following this tutorial he can move the mouse up and down, and left and right correctly

The script used was

posY += Input.GetAxis("Mouse X") * mouseSensitivity;
posX -= Input.GetAxis("Mouse Y") * mouseSensitivity;
// mouseSensitivity can be changed

Vector3 targetRotation = new Vector3(posX, posY);
transform.eulerAngles = targetRotation;

Due to the new Input System, using Input.GetAxis(“Mouse X”) throws an InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings error.

So I tried to use

private PlayerInputMovement inputCamera;

void Awake(){
   inputCamera = new PlayerInputMovement();
   inputCamera.Player.Camera.performed += context => cameraInput = context.ReadValue<Vector2>();
}

void Update(){
   Camera();
}

void Camera(){
   posY += cameraInput.x * mouseSensitivity;
   posX -= cameraInput.y * mouseSensitivity;
   // mouseSensitivity can be changed

   Vector3 targetRotation = new Vector3(posX, posY);
   transform.eulerAngles = targetRotation;
}

And got this, but if I keep my mouse on an axis, it keeps rotating to that side

So… is this a correct way to replace the old Input.GetAxis(“Mouse X”) or Input.GetAxis(“Mouse Y”) to the new Input System? How can I stop it from keeping rotating?

Thanks! :smile:

I think you have two options to fix your problem:

  1. Also subscribe to the ‘canceled’ event to get a callback when the input returns to zero:
void Awake(){
   inputCamera = new PlayerInputMovement();
   inputCamera.Player.Camera.performed += context => cameraInput = context.ReadValue<Vector2>();
   inputCamera.Player.Camera.canceled += context => cameraInput = context.ReadValue<Vector2>();
}
  1. Do polling in Update() instead of using the events:
void Camera(){
   var cameraInput = inputCamera.Player.Camera.ReadValue<Vector2>();
   posY += cameraInput.x * mouseSensitivity;
   posX -= cameraInput.y * mouseSensitivity;
   // mouseSensitivity can be changed
   Vector3 targetRotation = new Vector3(posX, posY);
   transform.eulerAngles = targetRotation;
}
1 Like