Inverse Kinematics: How One Line of Code Gave my NPC More Life

Giving Life to a Monster by using Inverse Kinematics.

Posted by on

## Creating the NPC

Over the last week or so I created a new NPC for my game which would be used as a mid-tier type boss character.

As with most of the things I create, I like to spend a day or so setting out a scene of how I imagine it to look in the final game. These 2 images were created to set the tone and feel of how I wanted this encounter to be.

## The In-Game Test

After a few days putting him into the game, I spent a lot of that time making the scenery destructible.

I created a small Play Pen to test out the dynamic scene damage as seen here: Youtube.com

## Adding "Look At" Inverse Kinematics

In the clip above you will notice that his head doesn't move to look at the player at all. Whilst this is acceptable (I was pretty pleased with the overall result) I explored the use of IK Look At.

All it took was this single line of code:

anim.SetLookAtPosition(Camera.main.transform.position);

Additional tweaks help make it more natural such as:

// MAKE HEAD TURN SLOWLY TOWARDS PLAYER AND ONLY WHEN IN-FRONT

if (Vector3.Dot(transform.TransformDirection(Vector3.forward), transform.position - lookTarget.position) < 0) lookWeight = Mathf.Lerp(lookWeight,1f,Time.deltaTime*lookSmoother);
else lookWeight = Mathf.Lerp(lookWeight,0f,Time.deltaTime*lookSmoother);

// SET THE RATIO OF HEAD AND BODY MOVEMENT

anim.SetLookAtWeight(lookWeight,0.2f,0.9f,1f,1f);

Here is the same demonstration but with the new IK Look At implemented: Youtube.com

Post a comment
Sign in or join with:

Only registered members can share their thoughts. So come on! Join the community today (totally free - or sign in with your social account on the right) and join in the conversation.