Search Unity

Attaching a HingeJoint2D at runtime?

Discussion in 'Scripting' started by spectre1989, Aug 30, 2017.

  1. spectre1989

    spectre1989

    Joined:
    Oct 6, 2009
    Posts:
    125
    Hey guys,

    I have a GameObject with a disabled HingeJoint2D, and during play I want to attach a Rigidbody2D to it at runtime such that it attaches midway between the min and max limits.

    It seems that the limits you set in the joint are relative to the rotation of the rigidbody at the time you attach it (which seems odd to me). So I've tried this:

    Code (CSharp):
    1. hingeJoint2D.connectedBody = rb2d;
    2. rb2d.rotation = 0.0f;
    3.  
    4. hingeJoint2D.enabled = true;
    5.  
    6. rb2d.rotation = (hingeJoint2D.limits.min + hingeJoint2D.limits.max) * 0.5f;
    It kind of works, but sometimes does some spinning when first attached.

    Any ideas?
     
  2. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    "It seems that the limits you set in the joint are relative [...] at the time you attach it". That's also my experience. When you attach a 3D joint, the current position and rotation are locked as the base pos (in variables you can't see.)

    I think your problem is setting rb2d.rotation _after_ attaching it, so it thinks the original rotation is where it wants to be (disclaimer: I've never used 2D joints, this is from memory moving 3D ones in realtime.)