Driving characters with Inverse Kinematics in Unity
Inverse Kinematics is a mechanisms in Unity where you specify constraints, such as where hands should be, or where the head should turn towards, and Unity computes the rest of the body's limbs to satisfy those constraints.
Before reading this post, you should try it out yourself by following these:
Initial set up
- On the character GameObject (the one with the AnimationController), add a Rig Setup component.
- Under the character, create a GameObject, and add a Rig component to it.
- Drag your Rig GameObject to the Rig Setup.
- Under the Rig GameObject, add child objects with individual constraints on them, eg "LeftHandConstraint".
Constraints on hands
The usual way is to set up a Two Bone IK Constraint.
- Assign the tip as the hand
- Click on ..., then on Auto Setup from Tip Transform.
This assigns the mid and root for you, and also creates two children: the target and the tip. The target is where the hand should be, and the tip is how the elbow should be oriented.
If you run it, you'll see that the hand is now on the target. You might run into issues where the hand orientation is off compared to the object it's supposed to hold. That's because the hand's local Z might not point to the direction you expect. Let's fix that.
Using the Maintain Target Offset parameter
It is possible to maintain a target offset, which is the initial offset between the tip and the target.
However in my case, the initial positions are not related.
Using matching transforms
The way I do it is:
- Duplicate the object I want the hand to hold later, like a sword.
- I then place the duplicate object in the Tip, eg the hand.
- I position the object how I'd like it to be when it's held.
- In the object's Target child, eg where the hand will be, I add an empty GameObject, and name it Offset.
- I select Offset, then the Hand, and go into Animation Rigging, Align Transform. This will make it so that I can later re-orient the Target in a way that's easy for me to understand, and the hand will readjust accordingly.
- Now that the offset has been computed, I move the duplicate object (the sword) out of the character so that its coordinates are in world space like the original object.
- I align the transform of the duplicate so that it matches the original. Now the Offset object is oriented correctly (in world space) compared to the original object.
- I move the Offset object to the Target.
- In the Constraint, I select that Target as the target.
I admit that this is a bit hard to read. I'll add more screenshots later or make a video.
Constraints on the Head
Usually I use a chain constraint.