Firing towards mouse- aim in all directions?

I am using this code to fire a bullet (‘launch’ prefab) from the player towards the mouse position

(in Update)

}if(Input.GetKeyDown("b")){
		
		var distFromCam = Camera.main.transform.InverseTransformDirection(transform.position).z ;
		var targetScreenPos = Input.mousePosition;
        targetScreenPos.z = distFromCam;
        var targetPosition = Camera.main.ScreenToWorldPoint(targetScreenPos); 

		
			var go: GameObject = Instantiate(launch, fire.position, transform.rotation);
			go.transform.LookAt(targetPosition);

I think this is only paying attention to the camera’s actual position instead of its position and rotation- When the camera rotates around 180, it will still only fire on the world axis’ z from the camera. How do I tell this to pay attention to the camera’s z rotation? Thanks

This approach will not work, because you can’t figure out the distance from the camera to the point you want to shoot. You should use ScreenPointToRay and Physics.Raycast (see example here) to find the world point “under” the mouse pointer:

if(Input.GetKeyDown("b")){
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit: RaycastHit;
    if (Physics.Raycast(ray, hit)){ // executes only if some object hit (sky doesn't count)
        var targetPosition = hit.point; 
        var go: GameObject = Instantiate(launch, fire.position, transform.rotation);
        go.transform.LookAt(targetPosition);
        ...
    }