Search code examples
unity-game-enginegame-physics

Unexpected spinning behaviour in zero gravity with Unity ConfigurableJoint


I have two cubes connected by a ConfigurableJoint, floating in zero gravity. XYZ motion is locked and angular XYZ motion is limited. In certain joint configurations, when I set the Target Rotation the cubes push against one another and start spinning, seemingly creating angular momentum out of nowhere. Any ideas as to where this spinning behaviour comes from, and is there a way to prevent it?

spinning

So far my best attempt at solving this has been to try to detect when joints are in a state that may induce spinning, and then apply a weakening factor to the joint motor. Accurately detecting this has proven difficult, however.


Solution

  • It turns out that the spinning occurs when the joint anchor becomes separated from the joint connected anchor.

    spinner, showing separated anchors

    As there doesn't seem to be a good way to prevent this from happening, my solution is to instead detect when separation occurs, then apply a weakening factor to the joint motor.

    private void FixedUpdate()
    {
        Vector3 diff = transform.TransformPoint(joint.anchor) - joint.connectedBody.transform.TransformPoint(joint.connectedAnchor);
    
        jointDrive.maximumForce = Mathf.Lerp(jointDrive.maximumForce, maxForce * Mathf.Max(0, 1f - 1000f * diff.magnitude), Time.fixedDeltaTime);
    
        if (joint.angularXDrive.maximumForce != jointDrive.maximumForce)
            joint.angularXDrive = jointDrive;
        if (joint.angularYZDrive.maximumForce != jointDrive.maximumForce)
            joint.angularYZDrive = jointDrive;
    }