- Home /
Vector3.Lerp snaps when called too frequently.
Hey.
I have a problem with my code where the Vector3.Lerp method snaps into it's target position instead of interpolating to it properly when called too frequently. Here is the class handling this:
public class c_toggleCamera : MonoBehaviour
{
public Transform[] tgt;
public int index;
public float speed = 1.0F;
void Start()
{
transform.position = tgt[0].position;
transform.rotation = tgt[0].rotation;
}
public IEnumerator MoveToSpot(int i)
{
float elapsedTime = 0;
Transform currentPos = transform;
Transform targetPos = tgt[i];
while (elapsedTime < speed)
{
transform.position = Vector3.Lerp(currentPos.position, targetPos.position, (elapsedTime / speed));
transform.rotation = Quaternion.Lerp(currentPos.rotation, targetPos.rotation, (elapsedTime / speed));
elapsedTime += speed*Time.deltaTime;
yield return null;
}
transform.position = targetPos.position;
transform.rotation = targetPos.rotation;
index = i;
yield return null;
}
}
How could i smooth this out?
Have you tried altering the float variables? Because in this case it seems to me that the interpolation is happening in 1 frame. ElapsedTime / speed will be more than 1 after the first frame. Try this:
float length = 300;
float speed = 1;
public IEnumerator $$anonymous$$oveToSpot(int i)
{
while(elapsedTime < length)
{
transform.position = Vector3.Lerp(currentPos.position, targetPos.position, elapsedTime / length);
// Same for the rotation
elapsedTime += speed * Time.deltaTime;
yield return null;
}
}
No, that's not my problem. It interpolates fine with the code i provided. $$anonymous$$y issue occurs when i try to call $$anonymous$$oveToSpot(x) again while it's still interpolating to another destination. This causes it to either snap to it's new destination without any interpolation, or "bounce" in a strange way before getting to it's destination. On some occasions, both of the side effects mentioned above occur together.
I tried your code, but it slows down to a halt before reaching it's destination.
Answer by tadadosi · Jun 01, 2020 at 04:53 PM
My guess is that the coroutines are overlapping and that you should probably stop the current routine before starting MoveToSpot(x) again. Unity Docs StopCoroutine
Answer by Captain_Pineapple · Jun 01, 2020 at 05:04 PM
Your problem is that you do not save a position (which would be a copy by value) but instead save a reference to a transform. In the end this means that currentPos.position does not really resemble the starting point but instead always is the actual current position of the object you are moving.
So your problem should be solved if you just change the currentPos from beeing a Transform to a Vector3 currentPos = transform.position;
same should probably be done for the target transform as well.
this will then result in actual linear movement. You still probably have to reduce your speed though.