What is the best way to constrain bone rotations?

I have a fully rigged FBX which works fine in Unity when I am controlling it's movement via Kinect (I am not using pre-existing animations mostly). I am not using any IK or anything. However I would like to constrain the movements of each bone based on normal human limitations - to do that I have a series of constants Vector3's with the bindpose, jointMin and jointMax rotations and I am attempting to only rotate the bone when the value is within these values but it is clumsy and hard to debug.

Is this the correct approach? I see in the docs there are some joint constraints but I assume that is for a different type of object in Unity, and would require me to re-rig my character in a different way? I would prefer to keep my character rigs created in my external 3D app and just set settings or code in Unity and I am using Z-axis bones from Lightwave in my generated FBXs.

Are there any links or tutorials on constraining bones from such a rig? Or what is the best approach? thanks :)

5 Answers

5

Well, I modified psdev’s code to include constraints on multiple axes. I know this answer is old, but hopefully this helps someone.

EDIT: Also, this code can be attached anywhere. All you have to do is assign each of the bones to the BoneClamp array. I usually attached this to the GameObject of the player model I’m constraining.

    using UnityEngine;
    using System.Collections;
    
    [AddComponentMenu("Kinect/Kinect Clamp")]
    
    public class KinectClamp : MonoBehaviour {
    	
    	[System.Serializable]
    	public class BoneClamp{ //Class for bones with min and max XYZ rotation values
    		public Transform bone;
    		public float minX = 0;
    		public float maxX = 360;
    		public float minY = 0;
    		public float maxY = 360;
    		public float minZ = 0;
    		public float maxZ = 360;
    	}
    
    	public BoneClamp[] boneClamps;
    	private Vector3 newV3 = new Vector3(0f,0f,0f);
    
    	// Use this for initialization
    	void Start(){
    		
    	}
    
    	// Update is called once per frame
    	void Update(){
    		foreach(BoneClamp clamp in boneClamps){ 
    			clamp.minX = Mathf.Clamp(clamp.minX,0,360);	
    			clamp.minY = Mathf.Clamp(clamp.minY,0,360);	
    			clamp.minZ = Mathf.Clamp(clamp.minZ,0,360);	
    			clamp.maxX = Mathf.Clamp(clamp.maxX,0,360);	
    			clamp.maxY = Mathf.Clamp(clamp.maxY,0,360);	
    			clamp.maxZ = Mathf.Clamp(clamp.maxZ,0,360);	
    		}
    	}
    
    	// We use LateUpdate to grab the rotation from the Transform after all Updates from
    // other scripts have occured
    	void LateUpdate(){
     		foreach(BoneClamp clamp in boneClamps){
    			float rotationX = clamp.bone.localEulerAngles.x;
    			float rotationY = clamp.bone.localEulerAngles.y;
    			float rotationZ = clamp.bone.localEulerAngles.z;
    			
    			rotationX = Mathf.Clamp (rotationX, clamp.minX, clamp.maxX);
    			rotationY = Mathf.Clamp (rotationY, clamp.minY, clamp.maxY);
    			rotationZ = Mathf.Clamp (rotationZ, clamp.minZ, clamp.maxZ);
    			
    			newV3.x = rotationX;
    			newV3.y = rotationY;
    			newV3.z = rotationZ;
    			
    			clamp.bone.localEulerAngles = newV3;
    		}
    	}
    
    }

Thank you, it sure did help me.

I converted some code to C# that I found in this tutorial on google code: http://code.google.com/p/see-saw-unity/source/browse/trunk/see-saw-unity/Assets/Standard+Assets+%28Mobile%29/Scripts/RotationConstraint.js?r=2

It pretty much works, though I am still looking for the best way to constrain on multiple axis at a time. This works on one axis if you apply this script to the bone in question and set the properties in the inspector. Here is my C# conversion:

using UnityEngine;
using System.Collections;

public class AxisConstrainer : MonoBehaviour 
{

public enum ConstraintAxis
{
    X = 0,
    Y,
    Z
}

public ConstraintAxis axis;        // Rotation around this axis is constrained
public float min;                  // Relative value in degrees
public float max;                  // Relative value in degrees
private Transform thisTransform;
private Vector3 rotateAround;
private Quaternion minQuaternion;
private Quaternion maxQuaternion;
private float range;

// Use this for initialization
void Start () 
{
    thisTransform = transform;

    // Set the axis that we will rotate around
    switch ( axis )
    {
            case ConstraintAxis.X:
                    rotateAround = Vector3.right;
                    break;

            case ConstraintAxis.Y:
                    rotateAround = Vector3.up;
                    break;

            case ConstraintAxis.Z:
                    rotateAround = Vector3.forward;
                    break;
    }

    // Set the min and max rotations in quaternion space
    minQuaternion = thisTransform.localRotation * Quaternion.AngleAxis( min, rotateAround );
    maxQuaternion = thisTransform.localRotation * Quaternion.AngleAxis( max, rotateAround );
    range = max - min;  
}

// Update is called once per frame
void Update () 
{

}

// We use LateUpdate to grab the rotation from the Transform after all Updates from
// other scripts have occured
void LateUpdate() 
{
    // We use quaternions here, so we don't have to adjust for euler angle range [ 0, 360 ]
    Quaternion localRotation = thisTransform.localRotation;
    Quaternion axisRotation = Quaternion.AngleAxis( localRotation.eulerAngles[(int)axis ], rotateAround );
    float angleFromMin = Quaternion.Angle( axisRotation, minQuaternion );
    float angleFromMax = Quaternion.Angle( axisRotation, maxQuaternion );

    if ( angleFromMin <= range && angleFromMax <= range )
    {
        return; // within range
    }
    else
    {               
        // Let's keep the current rotations around other axes and only
        // correct the axis that has fallen out of range.
        Vector3 euler = localRotation.eulerAngles;                  
        if ( angleFromMin > angleFromMax )
        {
                euler[(int)axis ] = maxQuaternion.eulerAngles[(int)axis ];
        }
        else
        {
                euler[(int)axis ] = minQuaternion.eulerAngles[(int)axis ];
        }
        thisTransform.localEulerAngles = euler;         
    }
}

}

I am not marking my question as answered because this does not fully solve constraining on multiple axis yet and someone might have a better solution.

unfortunately I have not found a better solution yet. I don't get how other 3D apps like Lightwave can easily convert back and forth between Euler and Quaternion without losing reference to where you are in the 360 degrees (as this image shows Unity does http://i.imgur.com/5Ujig.gif )but yet Unity gives me useless degrees back. There is an IK solution on the Asset Store, but I haven't been able to get it to work with a complex rig, it seems to work fine with an arm by itself though. Search for IK in the Asset Store - it's the only one there and maybe you can make sense of it.

Usually converting to Euler representation and checking/clamping the x value to a x-min x-max etc is the easiest way.

Check this link out in case it helps. It shows what my current skeleton hierarchy is, what the local bind pose angles are, and what I'd like to use as MIN and MAX limits for each of the bones in my character: http://pastebin.com/PmcHqHea

I used to have a code i applied on an ik leg to constrain it and all i did was check if eurler.x was within region. Obviously if your neutral / rest position is not 0 you would need to wrap/warp the angle i.e do some form of matter mathematical shift that places the min at zero and the max < 360 usually its simply a +offset Angle problem. You might want to check ODE , any opensource physics engine on how they constrain joints.

My solution deals with the notion that bindspace joint orientations could be entirely horrible… and that’s ok - we don’t require that joints be oriented in any particular way.
The thrust of my solution, is to compute reference direction vectors in the bindpose, and use them as a basis of comparison in order to determine change in direction/orientation, which can be most efficiently constrained in the local space of a parent joint.
Currently, before I do anything much else, I grab a copy of the (parent-relative) local transforms of all joints… I compute the Direction from Parent to each Child, transformed into the (bindpose) local space of the parent. I keep these as a reference.
At runtime, when a new Direction has been computed, (ie both forward and backward Fabrik passes have been performed, with NO regard to angular constraint), I’m able to compare the two direction vectors (again, in the local space of the parent), and extract a rotation that would rotate my reference vector to align with the new vector. I have now got a ‘delta-rotation’ that could be multiplied with the parent worldspace rotation in order to achieve the desired new direction - I multiple the rotations, such that I have a new worldspace orientation for the parent, then I apply my per-axis angular constraints (as posted above, by Drod7425), I apply this transform to my parent, and finally, I transform the reference direction from parentspace to obtain the new childspace position, which automatically imposes the length constraint. We only need to correct child position, since directions are recomputed every frame, and so this can be easily incorporated into the Backward Pass.