[Unity] How to achieve any linear effect elegantly?

In games, we often want to achieve some animation effects. For example: objects rotate slowly, move along irregular routes, UI fades in and out, color changes, etc.
In fact, behind these effects are all related to a function – Lerp
Once you understand and master this function, it is very simple for you to achieve the above effects.
In this article, I will share:

  • Experience
  • Misunderstandings
  • movement on irregular routes

What is linear interpolation?

Any value between the two vectors. As shown in the figure:
vector A, vector B. The line segment AB between them. The value between the line segment AB is linear interpolation.
image.pngimage.png

Corresponding Unity's Lerp function Lerp(A, B, ratio t);
when the ratio range is 0~1: when
the ratio is 0, the interpolation is equal to point A.
When the ratio is 1, the interpolation is equal to point B.

What are the Unity Lerp related functions?

  • Material.Lerp : interpolation between materials
  • Vector2.Lerp : interpolation between vectors
  • Vector3.Lerp : interpolation between vectors
  • Mathf.Lerp : interpolation between floating point numbers
  • Color.Lerp : interpolation between colors

So far, if you understand what is linear interpolation. Then you should know how to use it in Unity.
But if you're content with that. You may be missing some details, resulting in suboptimal results.

Experience

move

Let's simply use the Lerp function to move the object within 1S.
code show as below:

public class Lerp : MonoBehaviour
{
    // 终点
    public Vector3 targetPosition;
    // 开始位置
    public Vector3 startPosition;
    // 持续时间
    public float lerpDuration = 1f;
    // 记录运行时间
    private float _timeElapsed = 0;

    private void Start()
    {
        transform.position = startPosition;
    }

    void Update()
    {
        // 记录这一帧移动的位置
        Vector3 valueToLerp;
        _timeElapsed += Time.deltaTime;
        if ((_timeElapsed < lerpDuration))
        {
            valueToLerp  = Vector3.Lerp(startPosition, targetPosition, _timeElapsed / lerpDuration);
            transform.position = valueToLerp;
        }
        else
        {
            valueToLerp = targetPosition;
        }
        transform.position = valueToLerp;
    }
}

Effect:
Lerp.gif

Ok, such a moving effect is complete.

Take any point on the line segment

From another angle, we can also obtain the coordinates of any point on the AB line segment.

code show as below:

public class GetPoint : MonoBehaviour
{
    // 坐标点A
    public Vector2 a;

    //  坐标点B
    public Vector2 b;

    // 比值
    public float ratio;

    private void Update()
    {
        var position = Vector3.Lerp(a, b, ratio);
        transform.position = position;
    }
}

The effect is as follows:
Take any point on the line segment.gif

The other linear change effects are actually the same, but the function method you use may be different.

Text fades in and out

![Fade in and fade out.gif](https://cdn.nlark.com/yuque/0/2022/gif/1256055/1664379245737-f3395f14-280e-47d8-a7f4-3d1f62348c5a.gif

public class FadeToBlack : MonoBehaviour
{
    public float targetValue = 0;
    CanvasRenderer elementToFade;
    void Start()
    {
        elementToFade = gameObject.GetComponent<CanvasRenderer>();
        StartCoroutine(LerpFunction(targetValue, 0.8f));
    }
    IEnumerator LerpFunction(float endValue, float duration)
    {
        while (true)
        {
            float time = 0;
            float startValue = elementToFade.GetAlpha();
            // 淡出
            while (time < duration)
            {
                elementToFade.SetAlpha(Mathf.Lerp(startValue, endValue, time / duration));
                time += Time.deltaTime;
                yield return null;
            }
            elementToFade.SetAlpha(endValue);
        
            // 淡入
            time = 0;
            while (time < duration)
            {
                elementToFade.SetAlpha(Mathf.Lerp(endValue, startValue, time / duration));
                time += Time.deltaTime;
                yield return null;
            }
           elementToFade.SetAlpha(startValue);
        }
    }

}

gradient

Gradient.gif

public class LerpMaterialColour : MonoBehaviour
{
    
    private Text text;
    public Color targetColor = new Color(0, 1, 0, 1); 
    void Start()
    {
        text = gameObject.GetComponent<Text>();
        StartCoroutine(LerpFunction(targetColor, 5));
    }
    IEnumerator LerpFunction(Color endValue, float duration)
    {
        float time = 0;
        Color startValue = text.color;
        while (time < duration)
        {
            text.color = Color.Lerp(startValue, endValue, time / duration);
            time += Time.deltaTime;
            yield return null;
        }
        text.color = endValue;
    }
}

Misunderstandings

We may have encountered it in ordinary times, and there is the effect of using the Lerp function to achieve smooth movement.
The effect is as follows:
Smooth Movement - Lerp.gif
the code is as follows:

public class Lerp_Error1 : MonoBehaviour
{
    // 终点
    public Vector3 targetPosition;
    // 开始位置
    public Vector3 startPosition;
    
    private void Start()
    {
        transform.position = startPosition;
    }

    void Update()
    {
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);
    }

❎ This usage is actually incorrect. Because it is actually changing the initial value, the "interpolation" is obtained by changing the distance between A and B. This is no longer a linear interpolation calculation.
image.png

Moreover, to achieve the effect of smooth movement, we can actually use the SmoothDamp() method. For specific usage, please refer to this article TODO.

How to achieve irregular movement?

Irregular movement.gif

Just now we have easily achieved linear motion, if we can summarize the irregular route with a straight line, it seems that the object is just moving in a multi-segment straight line.
Irregular motion split.gif

If you think it's good, you can give it a thumbs up. Your love is my greatest motivation.

Guess you like

Origin blog.csdn.net/GG_and_DD/article/details/127195067