IEnumerator SmoothlyShiftPosition(Vector3 destination, float OverTime) {

    float startTime = 0;
    while (startTime < OverTime)
        Debug.Log(startTime/OverTime + "changing: " + navigationCanvas.transform.position);
        Debug.Log("startTime : " + startTime);
        navigationCanvas.transform.position = Vector3.Lerp(navigationCanvas.transform.position, destination, startTime/OverTime);
        startTime += Time.deltaTime * 2f;
        yield return null;
    navigationCanvas.transform.position = destination;

I have this simple code snippet which i am using to lerp my object to specfied position smoothly it work sometime correctly but not always. I logged different data and found that my startTime variable sometime becomes zero continuously. I am unable to figure why this occuring? what i am doing wrong?


I am calling coroutine function like this

 if (SmoothlyShiftPositionIEum != null) {
                       SmoothlyShiftPositionIEum = StartCoroutine(SmoothlyShiftPosition(navCanvas, smoothPositionTime));
  • \$\begingroup\$ Are you sure that you are not calling the coroutine multiple times? \$\endgroup\$ – Nikaas Apr 17 '17 at 8:52
  • \$\begingroup\$ @Nikaas good point i am checking that if coroutine is already running then sop it. like code updated above \$\endgroup\$ – Muhammad Faizan Khan Apr 17 '17 at 9:07
  • \$\begingroup\$ I don't think this change will fix it. You may need to add SmoothlyShiftPositionIEum=null at the end of the coroutine. Then only start the coroutine if SmoothlyShiftPositionIEum is null. \$\endgroup\$ – Nikaas Apr 17 '17 at 9:22
  • \$\begingroup\$ You might find the pattern described in this answer helpful. Be sure to check whether you're pausing the game anywhere by setting Time.timeScale to zero. This will pause any script that uses Time.deltaTime, making it idle in the same place until the time scale is restored. \$\endgroup\$ – DMGregory Apr 17 '17 at 11:49
  • \$\begingroup\$ @MohammadFaizanKhan If the Lerp part is working as intended you can ignore this. It's worth mentioning that you aren't "linear interpolating" since you constantly change the starting position of the lerp. If you want a true linear transition from A -> B you need to save your starting position and use that as value A. By using your modified position in the lerp value you'll actually get a curve transition where things speed up as they approach the target. Once again, if this what you want, the go for it. Just making sure. \$\endgroup\$ – Zebraman Apr 17 '17 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.