Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Unity 2D: Set targetjoint2d anchor position at mouse position in 2d

MasterMoniMasterMoni Member
edited May 2020 in Programming

Hello everyone,

I am currently working on a physics puzzle game in Unity using c#. I have a gameobject with a rigidbody2d, with a hingejoint2d component at the center holding it in place. This causes the object to only rotate around the center on impact.

To rotate the object manually I am using a targetjoint2d, together with my mouse. The target of the targetjoint2d is set at my mouse position. To rotate the object, I want to set the anchor of the targetjoint2d at the position of the mouse, when the onmousedown function is called. The problem I have is that the anchor is currently being set in world space, while the anchor position of the target joint is calculated from the distance of the gameobject center in local space.

I tried using transform.InverseTransfrompoint(), to convert the mouse position to the local space of the object, but with no success.

How do I set the anchor at the position of my mouse when I click?

Below is the code I used trying to rotate the object manually:

 public class Drag : MonoBehaviour
    public TargetJoint2D tarJoint;
    public bool moveAnchor = false;
    bool canDrag = false;
    private void FixedUpdate()
      if (!canDrag)
      if (Input.GetMouseButton(0) == false) // when the mouse button is no longer pressed...
        canDrag = false;
        tarJoint.enabled = false;
      } = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    void OnMouseDown()
      tarJoint.enabled = true;
      if (moveAnchor) // if true, the anchor is not set at the center of the object
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        tarJoint.anchor = transform.InvertTransformPoint(mousePos);
      canDrag = true;

This image shows the settings of the joints on my gameobject. It also has a rigidbody2d set to dynamic and a boxcollider 2d.


Sign In or Register to comment.