HingeJoint2D Fix for Unity
During my 2D physics game prototyping, I encountered peculiar behavior. This issue has been mentioned multiple times online, but without any clear solutions. Here’s my brief explanation and fix.
The root of the problem —When you deactivate and then activate an object that has a HingeJoint2D with set limits, it can behave erratically on occasion. Visually, the joint appears to stay within the designated limits. However, if you inspect the HingeJoint2D.jointAngle
property, you will notice that the angle often exceeds 180 degrees or falls below -180 degrees. This issue occurs when we reactivate the object. Prior to activation, the jointAngle
property is correct.
The solution — Adjust the joint limits so that jointAngle
remains within a new range.
private void OnEnable()
{
// Those are original limits we saved in Awake method
var limits = this.originalLimits;
if( Mathf.Abs( this.joint.jointAngle ) > 180 )
{
// Place limits in the same range as the joint angle
// Usually limits are in the range -180 to 180 or 0 to 360
// If the joint angle is outside of this range, i.e. 400 degrees, then the limits should be in the range 180 to 540
int jointAngleOffset = 360 * ( (int) this.joint.jointAngle / 360 + Math.Sign(this.joint.jointAngle) );
limits.min += jointAngleOffset;
limits.max += jointAngleOffset;
}
this.joint.limits = limits;
}