Problem with raycasting

Hello gents, i have been having a minor issue here lately, while the code executes alright, it does not seem to be working properly

private void PlaceTurret()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Initialize the ray // reference in document
            RaycastHit2D[] hits = Physics2D.RaycastAll(ray.origin, ray.direction); // Raycast points to objects stored in array
 
            if (hits.Length > 0 && hits[0].collider != null )
            {
                GameObject turret_ = BuildManager.Instance.Getturret;  // Get the turret;
                turret_.transform.position = hits[0].collider.gameObject.transform.position; // Make the turret position equal to position that was clicked
                if ((hits.Where(x => x.collider.gameObject.tag == "Turret" 
                    || x.collider.gameObject.tag == "Path").Count()) > 0) // If turret is placed on another turret or path, the user cannot place it
                {
                    
                    return;
                }
             
                else 
                {
                BuildTurret(BuildManager.Instance.Getturret); // Build the turret    
                }
                 
                }

            }
        }
    }

I have a script that uses raycasts to detect when i am clicking on a turret or the path, while it does place the turret on the map, it isn’t placed where it is supposed to be placed, rather it is being placed much further away than where i am clicking even though the raycast isn’t hitting anything.

If anyone has a way to make the raycast point better it would be helpful

I think your problem is in this line:

turret_.transform.position = hits[0].collider.gameObject.transform.position; // Make the turret position equal to position that was clicked

You are not using the point you clicked, instead, you are using the position of the object that was hit. This is not necessarily the same thing. You can use hits[0].point instead. This is the point in world-space where the ray and the collider intersect.

Ok i’ve tried adjusting the origin of the raycast but they are still being placed in the same distance

RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(ray.origin.x + 0.5f, ray.origin.y + 0.5f), ray.direction);