How do I pull a chain

I have a script so that i can drag object from one place to another, I also have a lantern hanging in a ball and chain fashion with each having hingeJoint2D wich is connected to the one above it but when i try and drag the ball to a new spot (even within the reach of the chain) it moves by itself to the spot and just keeps going as if still connected to the chain

{
    Vector2 difference = Vector2.zero;
    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    public void OnMouseDown()
    {
        difference = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - (Vector2)transform.position;


        rb.freezeRotation = true;

    }

    public void OnMouseDrag()
    {
        transform.position = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference;
    }

    public void OnMouseUp()
    {
        rb.freezeRotation = false;
    }
}

Keep in mind this kind of code bypasses the physics system:

With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.

This means you may not change transform.position, transform.rotation, you may not call transform.Translate(), transform.Rotate() or other such methods, and also transform.localScale is off limits. You also cannot set rigidbody.position or rigidbody.rotation directly. These ALL bypass physics.

Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.

https://discussions.unity.com/t/866410/5

https://discussions.unity.com/t/878046/8

ALSO, our very own @MelvMay has a great public repo on various 2D physics tricks here:

https://github.com/Unity-Technologies/PhysicsExamples2D

1 Like

Thanks man worked like a charm

2 Likes