# Understanding Lerp/Slerp

I am trying to smooth out accelerometer input and using lerp or slerp like this:

``````cam.transform.position = Vector3.Lerp(cam.transform.position, newcamPos, 0.018f);
``````

The camera position is being controled by the accelerometer change * 420 or so to amplify the movement. I need to keep the movement clamped to the accelerometer – so a tilting the device pans up to the max accel input and when tilted back to the starting point unpans to the original camera position.

When the accelerometer input is bouncing between 0 and 0.018 (which it always does sitting still), Lerp or Slerp both work well to get the jitter out. But when the accelerometer input is bouncing between 0.7 to 0.718 Lerp/Slerp seem to do nearly nothing. I don’t understand why? Obviously I am missing something. My goal is to smooth out the ‘jitter’ caused by accelerometer bouncing around ± 0.18 regardless of its position.

The Lerp function essentially does a weighted average of the two values when you pass a constant value for the interpolation parameter. The code you’ve posted won’t really do much to smooth out the movement. It takes a weighted average of the current position and the new position, but it is biased heavily toward the current position since you are using a small interpolation value. Effectively, this will just make the object move very slowly.

It is more appropriate to do the filtering on the accelerometer input rather than the position. Try something like:-

``````var oldAccel: Vector3;
var biasFraction: float = 0.75;

function Update() {
var accel: Vector3 = Vector3.Lerp(oldAccel, iPhoneInput.acceleration, biasFraction);

// Reaction based on accel value...

oldAccel = accel;
}
``````

You can vary the bias fraction between 0 and 1 until you get a good result.

thanks for the input. I have changed my code to lerping the iphone accel input but I’m having the same issue as before. Having the camera directly linked to the accellerometer leads to a jitter. From looking at the values returning from the device, it is always bouncing around +/- 0.18 to 0.34, causing the jitter. I thought I could lerp that out, but it is still there regardless of the bias used.

here is a quick video showing the issue (constant jitter):
http://www.gravityride.com/panda/jitter.mov
note: the jitter is 5x as bad as it is in the movie due to the movie framerate/compression masking a lot of it. you’ll still get the idea I think.

Here is my code:

``````    Vector3 oldAccel = Vector3.zero;
Vector3 accel = Vector3.zero;
float biasFraction = 0.18f;

void Update ()
{
accel = Vector3.Lerp(oldAccel, iPhoneInput.acceleration, biasFraction);

camPos = cam.transform.position;
camPos.y = -(dir.x * 200);
camPos.x = -(dir.y*200);

cam.transform.position = camPos;
cam.transform.LookAt(Box.transform.position);
oldAccel = accel;
}
``````

Thanks for any advice on how to do what I’m trying to do.