shoot ray from mouse cursor

I am shooting a ray from the mouse cursor to see what object I hit.
I have a gameObject that follows the mouse cursor like a gunsight.

I am shooting a gun .

The problem is that I am detecting collisions with objects that I should miss , when the mouse cursor moves above or below and object.

transform.position = Camera.main.ScreenToWorldPoint(mouseP);
fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, fwd * 100, Color.green);

if(Physics.Raycast(transform.position, fwd,out hit))
{
Debug.Log(“Hit=” + hit.collider.gameObject.name);

In this situation, the problem arises because you are overcomplicating things. You have a bit of code which as far as I can tell is intended to move the ‘crosshair’ to the position of the mouse:

transform.position = Camera.main.ScreenToWorldPoint(mouseP);

However, the mouse is a 2-dimesional object on the surface of the ‘window’ into your 3-dimensional world. As such, it shouldn’t really ever move!

If you want to shoot raycasts at the mouse’s position, it is as simple as using

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

This will create a ray with the correct position and direction to be used as a mouse-click detector.

As for drawing a crosshair, you can then use

transform.position = ray.GetPoint(however far away from the camera);

to determine the position of the crosshair object.