Inverse Kinematics (IK) in Unity is a technique used in animation to control the positions of particular parts of a character, such as hands or feet, while automatically calculating the positions of other parts of the character's skeleton. This is particularly useful for making realistic animations where characters need to interact with objects in the environment, such as picking up items or walking on uneven surfaces.
Here’s a simple example to demonstrate how you might implement inverse kinematics for a character's arm in Unity:
Example: Basic IK for an Arm
Step 1: Setup the Armature
- Start by creating a simple armature in Unity using bones. You might have three segments: Upper Arm, Forearm, and Hand.
Step 2: Use Unity’s IK System
Unity’s Animator component has a built-in IK system that you can use:
-
Create a New Animator Controller:
- Right-click in the Assets window and choose
Create > Animator Controller.
- Attach this Animator Controller to your character model.
-
Setup the Animator:
- Open the Animator window, and create an empty state. You can just create a simple idle animation for the sake of setting up IK.
-
Enable IK in the Animator:
- Ensure the Animator component on your GameObject has
IK Pass checked in the Animator setup.
-
Create a Script to Control IK:
using UnityEngine;
public class SimpleIKControl : MonoBehaviour
{
private Animator animator;
public Transform rightHandTarget;
public Transform lookTarget;
void Start()
{
animator = GetComponent<Animator>();
}
// Called by Unity's Animation system
void OnAnimatorIK(int layerIndex)
{
if (animator)
{
// Assuming weight is calculated outside this scope, for simplicity we set to 1
float weight = 1.0f;
// Set the right hand position and rotation
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, weight);
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, weight);
animator.SetIKPosition(AvatarIKGoal.RightHand, rightHandTarget.position);
animator.SetIKRotation(AvatarIKGoal.RightHand, rightHandTarget.rotation);
// Set the look at position
animator.SetLookAtWeight(weight);
animator.SetLookAtPosition(lookTarget.position);
}
}
}
Step 3: Attach the Script and Configure Targets
- Attach the
SimpleIKControl script to your character.
- Assign
rightHandTarget to an empty GameObject placed where you want the hand to reach. This could be a point in space representing, for example, a doorknob or a controller.
- Similarly, assign
lookTarget to a GameObject that the character should look at.
This simple setup demonstrates how you can use Unity's inverse kinematics to handle the position and rotation of a character's hand, as well as control the direction the character looks. For more advanced setups, you might want to adjust weights dynamically, add more control scripts, or integrate with other systems depending on the complexity and realism required.