You could use Camera.ScreenToViewportPoint https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
transform.position = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
}
I could change your code as this.
void Update()
{
Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
RaycastHit hit;
...
}