Setting Up an IK Weapon System in Unity! (2)
Continuing on from the previous article, let’s create and attach a new script to both our L_Hand and R_Hand objects called something like ‘SmoothLerp’. As the name suggests, this script will give us a smooth transition between our hands’ current position and their destination (which will be roughly wherever the gun is).
In this script, we’ll need either a public or serialised private Transform variable (‘target’) and a serialised float variable for our speed. Then, instead of the standard Update method, we’ll use a LateUpdate method to store our lerp code. This code will change the transform.position of whatever object the script is placed on using a Vector3.Lerp (passing in our _speed as one of the variables). It’ll also set this object’s transform.rotation to the target transform’s rotation, specifically using its Transform.rotation.eulerAngles value. We should end up with something that looks a bit like this:
Heading back into Unity, we’ll want to reconfigure our Hierarchy before continuing. Specifically, we’re going to want an empty GameObject under our Main Camera (named something like ‘GunPos’) as well as two empty GameObjects under our gun (‘HandPosition_L’ and ‘HandPosition_R’). By and large the Hierarchy for our Player should be looking something like this:
These new GameObjects are going to be used as the Targets for these SmoothLerp scripts, so on our L_Hand and R_Hand objects add these respective HandPositions to the public/serialised Target transform. Lastly, on the root object for our gun, add another SmoothLerp script and drag in our GunPos as the Target transform.
If you save this and give it a whirl in Play mode, what we should now have is our avatar’s hands and gun moving smoothly in whichever direction the player faces 😉