- Home /
How to create a simple lean function( just moving position)
I'm trying to create a simple Lean function (C#) for my first person controller. (As in when a player is leaning around a corner.)
It will be a script set on the camera. The first person capsule won't be moving.
I don't need the camera to rotate. I just want the camera to move it's position slightly to the left or right when the correct key is held down.
So when Q is held down the cameras position smoothly moves slightly to the left (translates by 1 maybe?. The camera will hold it's position at the left until the key is no longer held.
And when E is held down the camera's position moves slightly to the right and holds that position until the E key is lifted.
When either of the keys are lifted the camera smoothly returns to the default position in the center.
The first image shows what should happen when E is held and the second shows when Q is held. (But actually looking at those pics the movement is probably too much. :p)
Answer by Razacx · Jul 22, 2014 at 06:33 PM
For this I would use Vector3.Lerp() Make some script that manages the camera position relative to the player. so for example
camera.position = player.position + player.TransformDirection(offsetVector(x, y, z));
(and also set the rotation ofc)
offsetVector has 3 variables as you can see: x, y and z. y and z would be constants (height and distance behind the player).
x can have three states. leaning to the left, neutral and leaning to the right.
You can then use Vector3.Slerp() to interpolate x between these values depending on user input. The Scripting API gives some good examples how to use this function: http://docs.unity3d.com/ScriptReference/Vector3.Slerp.html
Thank you sir! I got it all up and working thanks to your tips!
Your answer
![](https://koobas.hobune.stream/wayback/20220613154722im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Calling GameObject's transform from list 1 Answer