Attaching a HingeJoint2D at runtime?

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:

hingeJoint2D.connectedBody = rb2d;
rb2d.rotation = 0.0f;

hingeJoint2D.enabled = true;

rb2d.rotation = (hingeJoint2D.limits.min + hingeJoint2D.limits.max) * 0.5f;

It kind of works, but sometimes does some spinning when first attached.

Any ideas?

“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.)