How to do it...

To use IK to interac with scene objects, follow these steps:

  1. Import the character to Unity. Make sure to have the Idle and Pickup animations and set the rig to Humanoid.
  2. Create an Animator Controller and assign it to the character.
  3. Make sure to check the IK Pass option in the layer properties of the controller.
  4. Drag and drop the Idle and Pickup animations into the controller. Make sure Idle is the default state.
  5. Create a Trigger parameter and call it Pickup. Also create a float parameter and call it PickupIK.
  6. Create two transitions:
    • IdlePickup with one condition: Pickup Trigger parameter. Exit Time should be set to false and Transition Duration set to around 0.1 seconds.
    • PickupIdle with no conditions. Has Exit Time should be set to true and Transition Duration set to around 0.1 seconds.
  7. Go to the character's Import settings in the Animations tab.
  8. Create a new Animation Curve and name it PickupIK (the name has to match the float PickupIK parameter name).
  9. Create a smooth curve with the minimum value of 0 and the maximum of 1. The maximum value should match the moment when the character reaches for the object. See the following image for reference:
PickupIK Animation Curve. The maximum value (1) matches the frame when character picks up the object
  1. Apply the import settings.
  2. Create a new script and call it PickUpIK.cs. In that script, we have a void OnAnimatorIK(int layerIndex) function. This function is called every frame in the IK Pass after all animations have been evaluated. In that function, we get the value of the PickupIK float parameter from the controller (which equals the value of the Animation Curve). Then we set this value as the weight for the left-hand IK. We also set the left-hand IK position to match a public Transform ikTarget member variable in which we store the reference to the object we want to pick up:
        ikWeight = anim.GetFloat("PickupIK"); 
        anim.SetIKPosition(AvatarIKGoal.LeftHand, 
        ikTarget.position); 
        anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, ikWeight) 
  1. In the Update() function of the script, we check if the player pressed the space bar and played the Pickup animation.
  1. Save the script and attach it to the character. Create a new game object that we want to pick up. Call it PickupObject and drag it to the Ik Target field in the script's Inspector.
  2. Play the game and press the space bar to see the effect. You may move the PickupObject in the Scene View and press the space bar again. Our character will still try to reach it (it may fail due to the limited range of its arms).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.205