Connecting HingeJoint2D to clicked upon spot

I’m creating a 2D game where the user can click and drag objects around. This is done by connecting a ‘Hand’ object to the object the user is current clicking on with a HingeJoint2D. Right now it simply connects the HingeJoint2D to the center of the clicked upon object.

I want to anchor the Hingejoint2D to the exact spot on the rigidbody (not the center) that the user is clicking on. This must involve transforming the clicked upon point to coordinates relative to the clicked upon rigidbody, but I’ve had no success using methods like transform’s TransformPoint.

Any help would be appreciated.

This is the code I have attached to the object that the user will be dragging around:

void OnMouseDown() {		
    // Create a hinge joint between the hand and this object so object will slowly rotate
    // around the hinge point
    this.gameObject.AddComponent("HingeJoint2D");
    connectingHinge = this.GetComponent<HingeJoint2D>();
    connectingHinge.connectedBody = handRigidbody;
    
    // Set anchor to offset of current hand position relative to the object.
    //connectingHinge.anchor = new Vector2(offset.x, offset.y);
}

Image of gameplay:

The gray box is where the mouse cursor is. The gun is an object that the user is dragging about while it is connected to the gray box with a HingeJoint2D.

I want to anchor the HingeJoint2D to the exact spot the user is clicking on, and not just the center of the rigidbody.

You need to create new GameObject (customCursor) as a child of the target object and make it follow your cursor like this:

Vector3 mousePos = Input.mousePosition;

mousePos.z = -10.0f;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);

customCursor.transform.position = mousePos;*

and then set HingeJoint position using customCursor’s LocalPosition:

HingeJoint2D hinge = gameObject.AddComponent().anchor = pos;

Hope it helps.