Home > Back-end >  How Lerp Scale and Lerp Position GameObject In Unity Same Time On Specific Position?
How Lerp Scale and Lerp Position GameObject In Unity Same Time On Specific Position?

Time:10-20

I need to lerp scale and lerp position GameObject in Unity in same time with this part of code, but gameobject scale first then set up the position.

    iTween.ScaleTo(gameObject, Scale, 1f);
    transform.localPosition = Vector3.Lerp(startPosition, positionToMoveTo, 1);

Also I try with this:

IEnumerator LerpPosition(Vector3 targetPosition, float duration)
{
    // startPosition = transform.position;
    while (time < duration)
    {
        transform.localPosition = Vector3.Lerp(startPosition, targetPosition, time / duration);
        transform.localScale = Vector3.Lerp(transform.localScale, Scale, time / duration);

        time  = Time.deltaTime;
        yield return null;
    }
    transform.position = targetPosition;
}

but I got same result.

Actually I need to zoom in on specific point of 2D sprite with these codes like in image:

enter image description here

Any help please?

CodePudding user response:

transform.localPosition = Vector3.Lerp(startPosition, positionToMoveTo, 1);

means ignore the startPosition and immediately jump to the positionToMoveTo. In general I would not merge tween with Coroutines, decide for either one of them.

In your other attempt there are also few odd things

  • You need to store the startPosition and startScale
  • You once use localPosition but in the start and end switch to position (= absolute world space) which might of course be quite different

So something like e.g.

IEnumerator LerpPositionAndScale(Vector3 targetLocalPosition, Vector3 targetLocalScale, float duration)
{
    var startPosition = transform.localPosition;
    var startScale = transfor.localScale;

    for(var timePassed = 0f; timePassed < duration; timePassed  = Time.deltaTime)
    {
        var factor = timePassed / duration;
        // [optional] add ease-in and -out
        factor = Mathf.SmoothStep(0, 1, factor);

        transform.localPosition = Vector3.Lerp(startPosition, targetLocalPosition, factor);
        transform.localScale = Vector3.Lerp(startScale, targetLocalScale, factor);

        yield return null;
    }

    transform.localPosition = targetLocalPosition;
    transform.localScale = targetLocalScale;
}
  • Related