Search code examples
unity-game-enginelerp

How to start Vector3.Lerp from middle point?


I have to move object from -10 to +10 x position. But I want to start my object from zero x.point to move, how can I start my lerp at the middle position?

Edit2: Object should start at x = 0 position and move to +10 x position and go to -10 x position and again +10 x, -10 x like a loop.

Vector3 pos1, pos2, pos0, pos3;
void Start()
{
    pos0 = transform.position;

    pos1 = pos0 + new Vector3(10, 0, 0);

    pos2 = pos0 - new Vector3(10, 0, 0);

    pos3 = pos1;
}
float time = 0.5f;
void FixedUpdate()
{ 
    time += Mathf.PingPong(Time.time * 0.5f, 1.0f);
    transform.position = Vector3.Lerp(pos2, pos1, time);
}

Solution

  • Here is how I would approach it:

    Vector3 ToPos;
    Vector3 FromPos;
    
    void Start()
    {
        ToPos = transform.position + new Vector3(10, 0, 0);
        FromPos = transform.position - new Vector3(10, 0, 0);
    }
    
    // using Update since you are setting the transform.position directly
    // Which makes me think you aren't worried about physics to much.
    // Also FixedUpdate can run multiple times per frame.
    void Update()
    {
        // Using distance so it doesnt matter if it's x only, y only z only or a combination
        float range = Vector3.Distance(FromPos, ToPos);
        float distanceTraveled = Vector3.Distance(FromPos, transform.position);
        // Doing it this way so you character can start at anypoint in the transition...
        float currentRatio = Mathf.Clamp01(distanceTraveled / range + Time.deltaTime);
    
        transform.position = Vector3.Lerp(FromPos, ToPos, currentRatio);
        if (Mathf.Approximately(currentRatio, 1.0f))
        {
            Vector3 tempSwitch = FromPos;
            FromPos = ToPos;
            ToPos = tempSwitch;
        }
    }