Search Unity

damping on Vector3.Lerp

Discussion in 'Scripting' started by ratamorph, Feb 27, 2008.

  1. ratamorph

    ratamorph

    Joined:
    Sep 2, 2007
    Posts:
    458
    I'm experiencing some weird damping with this statement.

    void FixedUpdate ()
    {
    if(targetSet)
    transform.position = Vector3.Lerp(transform.position, finalPosition, speed * Time.deltaTime);
    }

    Can anyone tell me why?
    The object moves just fine but toward the end the increments become very small, this is a problem because I'm trying to execute other code when the object finishes its translation and the game looks unresponsive because the increments are soo small you don't notice the object is still moving.
     
  2. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    This won't produce linear motion. If you're moving to 90% of the target position every time, for instance, it will appear to slow down as it reaches its destination. You're essentially doing this.

    If you want purely linear motion, store the initial position and lerp between that and the final position from 0-1.
     
  3. ratamorph

    ratamorph

    Joined:
    Sep 2, 2007
    Posts:
    458
    Damn that was quick, I changed it like this but now it only moves a little bit and then it stops.

    transform.position = Vector3.Lerp(startingPosition, finalPosition, speed * Time.deltaTime);

    I'm guessing it's the t value, how do I make it so it goes from 0-1 but at x speed?
     
  4. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    You're passing in a constant value now. Let's say your FixedUpdate() rate is the default of 50Hz, and your speed value is 2. This becomes:

    Code (csharp):
    1. transform.position = Vector3.Lerp(startingPosition, finalPosition, 2 * 0.02);
    So basically all that does is set the object's position to 4% of the way between the start and end position, each and every fixed update.

    There are easier ways to increment a value over time using coroutines. To stick with FixedUpdate(), though, you would just do something like:

    Code (csharp):
    1.  
    2. transform.position = Vector3.Lerp(startingPosition, finalPosition, pos);
    3. pos += speed * Time.deltaTime
    4.  
    Where pos is a float you're using to track the 0...1 progression.
     
  5. ratamorph

    ratamorph

    Joined:
    Sep 2, 2007
    Posts:
    458
    Perfect!!! thanks a lot Matt.