Что такое lerp напишите lerp для float
Об использовании и понимании функции Lerp в Unity3D
Приветствую хабровчан. Решил написать статью об одной теме, которую недавно затронул в общении со знакомыми людьми. Тема касается не столько использования, сколько понимания типового использования этой функции. Собственно, я — не особо программист, и не разработчик, так что мой взгляд — взгляд, так сказать, обывателя-дилетанта.
Написание статьи связано с общением с такими же как я непрофессионалами и выявлением некоторых разногласий по поводу поведения популярного куска кода с использованием функции Lerp в разных туториалах.
Нас интересует функция Lerp в Unity3D. А конкретнее, метод Lerp класса Vector3D. Впрочем, все «лерпы» в Юнити работают более или менее идентично. Итак, классический образчик использования Lerp в Юнити, фигурирующий во многих туториалах:
По идее, в данном коде объект, к которому относится скрипт, вместо моментального переноса в точку destinationPoint плавно туда передвигается. Код — по сути — простой. Однако, в его простоте есть определенные нюансы.
Первый момент возник, когда один человек, кинув взгляд, сказал, что этот код линейно интерполирует положение объекта из текущего в destinationPoint.
Собственно, функция Lerp — это и правда попросту линейная интерполяция. Но это сама функция. А вот действие кода вышеупомянутого метода Update уже не столь очевидно. При его применении видно, что объект сдвигается в нужном направлении, и по ходу дела замедляется. В случае же «истинной» линейной интерполяции объект должен начать движение, перемещаться с фиксированной скоростью, затем резко замереть. Именно так происходит, если обращаться к вариантам использования Lerp не из туториалов, а из официальной справки по скриптам (конкретно, по методу Lerp). А вот упомянутый код ведет себя не так.
Второй момент возник, когда другой человек сказал, что это вообще работать не должно. Функция Lerp должна принимать параметр (назовем его традиционно t), который меняется от 0 до 1. Соответственно, при нуле — положение соответствует начальной точке пути; при единице — конечной. Стало быть, когда параметр пробегает значения от 0 до 1 происходит перемещение от начальной точки к конечной. Но ведь в вышеуказанном коде параметр t практически не меняется! Переменная smoothing, задающая «гладкость» движения — фиксированна. deltaTime меняется в случайных пределах, но грубо-примерно находится на одном уровне; для постоянной частоты кадров она будет постоянна. Таким образом можно считать, что параметр t вообще не меняется, а значит и не будет меняться положение точки. И движения не будет.
Опять же, реальность показывает, что это не так. Код работает, и объект перемещается куда нужно. Еще и с замедлением.
Почему так происходит? Потому что положение начальной точки интерполяции меняется при каждом обновлении.
Примем для простоты, что частота кадров стабильная, и произведение параметра сглаживания на длину кадра равно 0.25 (одна четверть). Пусть нам надо пройти путь d от начальной точки до конечной:
В результате выполнения
получаем точку на расстоянии четверти от начала. Эта-то точка и становится новым положением объекта, и при следующем вызове метода Update() плясать мы будем уже от нее. Это к вопросу: почему это все же работает.
Новое расстояние d’ теперь меньше (поскольку объект придвинулся). Стало быть, четверть от этого расстояния будет тоже меньше. В итоге, объект сдвинется еще ближе к точке назначения, но уже на меньшее расстояние.
При следующем обновлении — объект пройдет еще меньшее расстояние.
Это уже к вопросу: почему используем линейную интерполяцию, а получаем нелинейное движение. Чем ближе объект к точке назначения, тем меньшее расстояние ему до него остается, но тем и меньше шаг, который он сделает, подобно объекту из апорий Зенона.
Фактически, объект движется к точке назначения по обратноэкспоненциальной зависимости, постоянно приближаясь к нему, но никогда не достигая. Ну, это с математической точки зрения. С практической же — зависит от выбранных масштабов.
Такое использование функции Lerp определенно имеет право на жизнь, но понятности оно не дает. Люди, услышавшие словосочетание «линейная интерполяция» часто предполагают другое поведение. Кроме того, есть много интересных фишек, позволяющих превратить интерполяцию из линейной в другую. Основаны они, обычно, на изменении параметра t. Фокус в том, что при использовании указанного примера все эти наработки вести себя будут совсем не так, как ожидалось. Я полагаю, разработчики Unity3D сами-то понимают функционирование подобного кода, но не объясняют таких нюансов, видимо не желая нагружать лишней (по их мнению) информацией.
Привычно функция Lerp и подобные ей используется для получения ряда промежуточных значений (как правило от начального до конечного). В данном же коде она нужна для получения одной конкретной точки: при каждом вызове Update() она находит значение точки, делящей отрезок пути в заданном отношении.
Еще звучал интересный вопрос, который я не совсем понял: коль скоро значение параметра интерполяции не меняется, зачем там вообще deltaTime? Ну, собственно, хорошая практика кодинга в Unity предполагает независимость от частоты кадров. Разумеется, при нестабильности частоты кадров разницу в поведении кода, что с умножением на Time.deltaTime, что без оного — на глаз не заметно. Но факт есть факт.
Другой вопрос, который уже задал я сам себе: зачем тогда умножать на Time.deltaTime в методе FixedUpdate()? Ведь разработчики уверяют, что время, проходящее между вызовами этого метода строго фиксировано (почти… см. ниже). Однако, в туториалах код, подобный вышеупомянутому, попадается и в методе FixedUpdate() (например, тут).
Тут возможно несколько вариантов: возможно, ведущие этой обучалки, привыкшие к данному шаблону, попросту вбили его не задумываясь. Либо же гарантировали идентичность результатов выполнения кода на случай, если по какой-либо причине частота обновления физики (вызовов FixedUpdate()) будет изменена. А может просто решили не добавлять «магических констант», а заодно обеспечить определенную совместимость (и переносимость) кода между методами Update() и FixedUpdate(), поскольку в противном случае пришлось бы иметь отдельные smoothing для первого и для второго метода.
Вообще, с этими временами обновления тоже не все гладко. Для FixedUpdate() заведена своя переменная fixedDeltaTime, которая, судя по названию, должна давать время между его вызовами… Но нет же, сами же разработчики рекомендуют и в FixedUpdate() и в Update() использовать deltaTime, поскольку частота вызовов FixedUpdate() фиксированная-фиксированная, да не очень.
Так или иначе, итог.
Функция Lerp — действительно функция линейной интерполяции. Однако, популярный шаблон ее использование вовсе не линейно интерполирует перемещение и вращение объекта. Код отличается определенной краткостью, хотя и вызывает затруднения при попытках применения наработанных методик изменения поведения линейной интерполяции. При этом, действие этого кода, насколько мне известно, нигде в обучалках не объясняется, оставляя многих в заблуждении относительно того, как он работает.
Вообще, я предпочитаю функцию SmoothDamp, которая, хоть и требует хранения дополнительной переменной, ведет себя более предсказуемо (позволяя, например, задать примерное время «прибытия» объекта на заданное место).
Русские Блоги
Анализ линейной интерполяции функции Lerp () в Unity3D
В unity3D, функция линейной интерполяции Lerp () часто используется для интерполяции между двумя, которые могут быть между двумя материалами, между двумя векторами, между двумя числами с плавающей запятой, между двумя цветами, Прототип функции выглядит следующим образом:
function Lerp(start : Material, end : Material, t : float) : void
Интерполировать между двумя материалами
static functionLerp (from : Vector2, to : Vector2, t : float) : Vector2
Линейная интерполяция между двумя векторами. Интерполировать от формы к в соответствии с числом т.
t находится между 0 и 1. Когда t = 0, вернитесь из. Когда t = 1, вернитесь к. Когда t = 0,5, верните среднее значение от и до.
static functionLerp (from : Vector3, to :Vector3, t : float) :Vector3
Линейная интерполяция между двумя векторами. Интерполировать от в до в соответствии с числом т.
static functionLerp (from : Vector4, to : Vector4, t : float) : Vector4
5. Mathf. Lerp интерполяция
static functionLerp (from : float, to : float, t : float) : float
На основе числа с плавающей точкой t возвращает интерполяцию между a и b, t ограничено 0
1. Когда t = 0 возвращается из, когда t = 1 возвращается в. Когда t = 0,5, возвращается среднее значение от и до.
6. Color.Lerp интерполяция
static functionLerp (a : Color, b : Color, t : float) : Color
Интерполируйте между цветами a и b через t.
static functionLerp (from : float, to : float, t : float) : float
На основе числа с плавающей точкой t возвращает интерполяцию между a и b, t ограничено 0
1. Когда t = 0 возвращается из, когда t = 1 возвращается в. Когда t = 0,5, возвращается среднее значение от и до.
Сначала давайте проведем эксперимент, запустим Unity3D, создадим файл сценария и введите в его Start () следующее:
void Start () <
print(Mathf.Lerp(0.0f, 100.0f,0.0f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.1f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.2f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.3f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.4f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.5f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.6f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.7f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.8f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,0.9f).ToString());
print(Mathf.Lerp(0.0f, 100.0f,1.0f).ToString());
>
Запустите Unity, консоль распечатает:
Этот эксперимент интерполирует между 0 и 100. Какое значение для вставки зависит от третьего параметра. Как видно из результатов печати, третий параметр является масштабным коэффициентом. Когда он равен 0,1, это означает, что длина от 0 до 100 составляет десятые доли. Один по той же причине 0,2 означает две десятых и т. Д. С этой точки зрения, интерполяция, которую мы буквально поняли в начале, состоит в том, чтобы вставить значение, которое можно понять таким образом.
Если мы изменим первый параметр в функции интерполяции в приведенном выше сценарии на 100.0f, второй параметр на 110.0f, а третий параметр останется неизменным, что вы думаете о результате операции? Не думайте, что это 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, фактический результат равен 100, 101, 102, 103, 104, 105, 106…. Поскольку интерполяция Интерполяция значения между исходными двумя числами означает, что эта функция сначала вычисляет чистое приращение на основе отношения, заданного третьим параметром, добавляет начальное число и, наконец, вычисляет интерполированное значение.
В разработке игр для Unity3D наиболее широко используется векторная интерполяция Vector3.Lerp. Ниже мы используем эту интерполяцию, чтобы угадать ее внутренний механизм реализации и некоторые приложения.
Пожалуйста, см. Рисунок ниже для значения координаты Y точки C:
EO / AO = DF / AF = CB / AC = 1-0,4 = 0,6, тогда значение координаты Y точки C EO = 0,6 * AO = 0,6 * 10 = 6.
Ниже мы используем интерполяционную функцию Vector3.Lerp в Unity3D: статическая функция Lerp (от: Vector3, до: Vector3,
t: float): Vector3 для расчета вычисленной выше интерполяции.
Мы переписали функцию Start () в предыдущем скрипте следующим образом:
Это согласуется с нашими результатами расчетов.
Для приведенного выше расчета для простоты две точки A и B сделаны специальными, что снижает сложность расчета. Для обычных A и B, как показано на следующем рисунке:
Функция Lerp больше используется в процессе разработки игры.В файле справки Unity мы перечислили два примера приложений Vector3.Lerp: один из них заключается в том, что позиция анимации перемещается от start.position к end.position за 1 секунду. конец:
// Следуем за целевым объектом как пружина
Давайте посмотрим на другой пример приложения.
Сначала установите пустой объект в точке поворота в соответствии с изгибом и волнистостью дороги. Значение позиции этого пустого объекта, то есть пространственные координаты, согласуются с дорогой здесь. Мы называем точку, где эти пустые объекты находятся, точкой поворота дороги. Эти точки связаны. Полилиния, состоящая из отрезков, прикреплена к поверхности дороги и является приблизительным путем этой дороги. Чем точнее эти точки, тем выше сходство между этой дорогой и дорогой.
Теперь мы используем этот путь, чтобы заменить эту дорогу, и поместим случайно сгенерированную баррикаду на этот путь, то есть на дорогу.
Предположим, что мы хотим генерировать контрольно-пропускной пункт каждые 100 метров до 200 метров, используйте переменную z + = Random.Range (100, 200), чтобы записать значение координаты Z контрольно-пропускного пункта (так как заключенные обычно бегут вдоль оси Z ) Затем в соответствии с этим значением Z-координаты определите, какие две точки в поворотной точке, между которыми задано значение координаты, и интерполируйте между этими двумя точками после нахождения масштабный коэффициент его интерполяции (функция Lerp () 3 параметра) можно рассчитать из известных значений Z-координат трех точек двух точек поворота и этой точки интерполяции, поэтому Vector3.Lerp
(от: Vector3, до: Vector3, t: float) Три значения параметров в функции известны, она может вычислить пространственные координаты этой точки интерполяции, в соответствии с предыдущим дизайном, эти две точки поворота Сегмент линии между ними помещается на дороге, тогда координата этой интерполяции находится на дороге, расположенная в соответствии с этой интерполяцией баррикада не будет отклоняться от дороги и будет поворачивать влево и вправо, когда дорога поворачивает влево, вправо Поверните направо, в гору и в гору, снова и снова в гору.
Конкретный процесс проектирования заключается в следующем:
Импортируйте модель дороги, предполагая, что она называется forest_1. Когда модель спроектирована, определяется, что ее длина составляет 3000, а начало координат находится на ее терминале. После импорта мы помещаем его в сцену вдоль положительного направления оси Z, так что значения X и Y его Transorm.Position равны 0. Мы можем импортировать многосегментные модели дорог одного типа и объединять их в длинные лесные дороги, контролируя их значения Z.
Таким образом, мы разделили извилистую дорогу на прямые участки и записали значения координат характерных точек на обоих концах каждого участка. С этими характерными точками есть также маршрут, близкий к дороге. Это метод превращения кривой в прямую, превращение изогнутой и волнистой дороги в отрезок, близкий к ней. Чем больше таких точек, тем выше степень сходства.
Создайте скрипт-компонент waypionts.cs на waypionts:
Gamedev suffering
Блог о разработке игр и серверных технологиях
Коротко про Lerp
Линейная интерполяция (Linear interpolation, которую ещё называют ‘lerp’ или ‘mix’) — очень удобная функция при разработке игр, которая интерполирует в диапазоне [от..до] на основе параметра t, где t обычно находится в диапазоне [0..1].
Другой пример: вы можете использовать линейную интерполяцию, чтобы плавно анимировать движение из одной точки в другую. Определите начальную точку (x1, y1) и конечную точку (x2, y2), затем интерполируйте измерения x и y отдельно, чтобы найти итоговую точку.
Или используйте линейную интерполяцию, чтобы прыгнуть к движущейся цели. Каждый кадр интерполировать от текущего значения к целевому значению с небольшим шагом t, к примеру, 0,05. Это всё равно, что сказать: приблизиться на 5% к цели за каждый кадр.
Пример посложнее — интерполирует один цвет (красный) в другой (синий). Чтобы сделать это, мы интерполируем (R, G, B) или (H, S, L) каналы цвета по отдельности, по аналогии с тем, как мы делали для 2D или 3D координат.
В комментариях заметили, что пример с телепортированием очень зависит от фреймрейта. Лучше учитывать deltaTime :
Game Dev Beginner
The right way to Lerp in Unity (with examples)
In Unity by John French April 13, 2020 47 Comments
Very often in Unity, you may want to animate a button, move an object to a new position, smoothly fade audio or graphics or, perhaps, change the colour of something gradually over time.
And for those tasks, as well as many others, you’re probably going to need to use Lerp, one way or another.
What is Lerp in Unity?
Lerp, or Linear Interpolation, is a mathematical function in Unity that returns a value between two others at a point on a linear scale.
Most commonly it’s used for moving or changing values over a period of time.
It’s an incredibly common feature of Unity, and development in general,
Surprisingly, it’s often misunderstood and can easily be used the wrong way, especially if you’re just getting started in Unity.
And, while this isn’t always a problem, it can lead to some unexpected results.
For example, it might mean that you can’t recreate the effect you want, or the Lerped animation may appear broken, or buggy or may not work at all.
Or, if you’re anything like me, you might occasionally forget how to use Lerp and need to look it up again every time you need to use it.
Which could be a lot.
But don’t worry, because that’s exactly what you’ll learn on this page.
In this post, I explain the basics of Lerp in Unity, when to use it and how to easily write a Lerp function (as well as how to add special effects, such as easing) with examples that you can use in your project.
What you’ll find on this page:
Let’s start with the basic method…
How to use Lerp
The first thing that you need to know about Lerp, that will make it much, much easier to use, is that the basic Lerp calculation is actually very simple.
It’s how it’s used that often becomes complicated and confusing.
Here’s how Lerp works…
The Lerp calculation returns a value from a known range, which is specified using a minimum and maximum value (a & b). For example, a range of 0-100.
The value that’s returned is defined by a third value, the interpolation point (t) which returns a point on the scale between a and b.
The interpolation point that’s passed in is a float value between 0 and 1. Essentially, acting as a percentage between a and b.
An interpolation point of 0 (0%) would return the minimum value (in this case also 0) while an interpolation point of 0.5 (50%) would return a value halfway between the minimum and maximum value (in this case, 50).
Here’s what it looks like in scripting:
And here are some examples:
In this example, Lerp is being used to return a float, but it’s also possible to Lerp other values, such as colours and Vector3 values (more on that later).
It works in exactly the same way, retrieving a mid-point value from a range using a percentage interpolation point.
And that’s all there is to it.
But how is that useful?
When would you use it?
And where does all the confusion come from?
The right way to use Lerp
Lerp can be used to create simple movement and animations.
A common use for Lerp is to produce an effect over a fixed period of time.
For example, to animate a button, fade the screen to black or move an object to a new position in a fixed amount of time.
This is done by increasing the interpolation point value from 0 to 1 over that duration.
Here’s how to do it:
For example, the script below will increment a value from 0 to 10 in 3 seconds time:
If you try this method, however, you’ll notice that the value doesn’t quite reach ten, often ending on a very close, but not exact, value. Such as 9.998 for example.
This is because the value that’s being used to measure if the Lerp is complete is time, not the actual value that’s being Lerped.
To fix this, ‘snap’ the value that’s being Lerped to the final target value after the Lerp is complete.
Like this:
Finally, because Lerp functions are often used to carry out an action over multiple frames, it can be helpful to place them in a Coroutine.
This makes them easier to write, easier to manage and, once they’re finished, they stop themselves.
Here’s the same example, written in a Coroutine:
When used in this way, Lerp is a simple, helpful method for creating animations and movement
Despite being simple, there are a surprising number of examples of Lerp being used the wrong way.
Or, at least, not in the way that Lerp is supposed to be used.
Lerp slowing down at the end (and how to stop it)
This slowing effect is actually a result of using Lerp the wrong way.
You may have seen this method of using Lerp before:
Although it’s used often, it’s not how Lerp is supposed to work.
The clue is in the name, Linear Interpolation.
And, while you can argue that the easing effect of the object slowing down is desirable, it has issues.
One of which is that the object will, most probably, never reach the target. It will just get closer and closer in ever-decreasing amounts.
This kind of movement can be very useful.
Especially when you want to ease an object constantly, and smoothly, towards another object every frame (i.e. not over a fixed time scale). For example, when creating a camera follow script, such as this one by Brackeys (YouTube).
There is a better way to do it.
While the Lerp method may work for you, Smooth Damp is specifically designed for just this kind of task.
It works in a similar way except that it will stop once it reaches the target (or at least, close enough) and it won’t overshoot.
Smooth Damp also works more smoothly, with some users having reported jerky movement when using the Lerp method which, although very slight, I also found to be true during my research for this article.
These methods create a constant, dampened movement towards another value.
But what if you want to Lerp over a fixed duration and you want to apply easing to the movement?
How to ease Lerp in and out (the right way)
When using Lerp over time, the change is even and linear.
This happens because the interpolation point value (t) that’s passed in is calculated by dividing time elapsed by the total duration and, every frame, increasing time elapsed by a linear amount (i.e. using Time.deltaTime).
But what if you don’t want linear movement?
What if you want to ease the start or end of the Lerp?
You can do this by modifying the interpolation point value after it’s calculated but before passing it into the Lerp function.
All you need is a formula, and which one you use depends on what kind of curve you want.
For example, the calculation below creates a Smooth Step Lerp movement:
This Lerp starts slow, is linear in the middle and then slows towards the end.
Here’s how it looks plotted over a chart:
And here’s what it looks like when applied to a Lerp movement script.
Notice the block speeding up as it starts and slowing down as it reaches the target:
Modifying the interpolation point value (t) eases the start and end of this movement.
Different easing effects can be achieved with different calculations.
For more curve formulas, try chicounity3d.wordpress.com or this article at febucci.com.
Alternatively, tweening assets, such as DOTween Pro, feature built-in easing options (more on DOTween later).
Using Lerp by speed (instead of time)
Another commonly promoted use of Lerp is to change a value at a fixed rate.
Typically this involves incrementing a speed value that’s multiplied by Time.delta Time and then passing that in as the interpolation point.
Usually, it looks something like this:
Surprisingly, this is used in the official Unity documentation on Lerp, where the example shown uses an interpolation value of 0.5f + Time.deltaTime.
As with the slow down method, this is not how Lerp is supposed to work.
However, unlike before, there’s no obvious reason to use this method.
The calculation, in this case, does not perform movement over a set period of time working, instead, at a set speed.
And while you could argue that’s helpful, there are easier options for doing exactly that.
For example, to increase any value by one unit per second, simply increment it by one multiplied by delta time each frame.
There’s no need to use Lerp.
Like this:
It’s also possible to move an object by a fixed speed using Move Towards, or rotate it with Rotate Towards.
So I’m not sure if this method of using Lerp to achieve a constant speed has a useful purpose.
And while I’m an advocate of using less conventional methods if they are easier to work with, or if they achieve a specific result when nothing else will do, using Lerp in this way seems to be more difficult.
But maybe I’m wrong…
Let me know in the comments if you’ve got a great reason for using Lerp like this.
When I use Lerp, the movement stutters and jerks. Why isn’t it smooth?
Sometimes when using Lerp, for example, to move an object, you may notice that the movement is not completely smooth, that it jerks around or appears bumpy.
For example the travel of the object stutters and jumps along its path, even though the movement is linear.
If this is happening to you, don’t worry.
While there are real issues that can cause this, the most likely reason is simply that you’re viewing it in the editor.
And, once you build the project, you’ll notice that the movement in the finished application is buttery smooth.
Examples of using Lerp
Lerp can be used to smoothly change all kinds of different values, such as floats, Vector3 values, Quaternions and colours.
Some values require slightly different methods, however, most of the examples on this page follow a simple layout.
Blank Lerp template:
This blank example will Lerp a float. Simply replace valueToChange with the value you want to Lerp.
But what about values other than floats.
What does it look like to Lerp those?
How to Lerp a Vector 3
In this example, pass in a Vector3 location for the position to move to, ideal for moving an object to a new position over a fixed duration.
This also works with a GameObject, just use GameObject.transform.position whenever you want to access the Vector3 position value of an object.
Here’s what Lerping a Vector 3 looks like in scripting:
Alternatively, try Move Towards to move to a set point at a fixed speed.
How to Lerp a Vector 2
The same method works for Lerping movement in 2D games as well, simply replace Vector3 with Vector2 and the same Lerp calculation will work.
Like this:
How to Lerp Rotation
Lerping Rotation is useful for rotating an object to an angle over a period of time.
In this example, the target rotation is passed in as a user-friendly Euler Angle (the Vector 3 angle you’re used to seeing in the Unity inspector).
However, it ‘s possible to deal with native Quaternions instead. Simply use a Transform reference as the target variable and pass in its direct rotation value.
In scripting, Lerping rotation with looks like this:
How to Lerp scale
This one works a little differently as it uses a modifier value to alter the scale.
This makes it easier to change the entire scale of an object by a single float value, without needing to use a Vector 3.
However, it also means that the current scale of the object is controlled by an arbitrary variable that is not natively accessible (e.g. like position or rotation are).
This means that to change the scale again, (for example, to scale up to twice the size only to then scale back down to the original size later) the scale modifier needs to be stored and accessible outside of the Lerp function.
This way, the relative scale is known and can be referenced if the function is used again.
Here’s what it looks like in scripting:
How to Lerp a Material’s Colour
Did you know you can Lerp colours too?
Well, you can! With Color.Lerp
You can set a target colour in the inspector or use RGBA values to control the colour and the alpha from scripting.
In this example, I’m setting a material’s colour to green:
Fade Camera to black using Lerp
It’s possible to fade any Canvas element with the Set Alpha method of the Canvas Renderer component.
When used with a full-screen black image that is drawn above all the other elements, this can be used to fade the Scene in or out:
How to fade out Text using Lerp
The Canvas Renderer method also works for other Canvas elements as well, such as Text.
Alternatively, the same effect can be achieved by Lerping the colour value of a Text object directly.
Like this:
Note that these examples use UI elements, so they require the using UnityEngine.UI namespace.
Fade out a sprite using Lerp
The same technique can be applied to changing the colour, and transparency of Sprites.
Typically the colour of a sprite is white, meaning that the sprite isn’t tinted a different colour.
So, to fade out a sprite, you’ll usually only have to store the existing colour if you’ve changed it, while Lerping the alpha value to 0 (transparent) or 255 (opaque) as you need.
Like this:
Fade out an Audio Source using Lerp
Fading an Audio Source over time, from its current value to a new value, uses a similar method as the other Lerp examples.
Setting the current value makes Lerp functions much easier to reuse, as you don’t have to worry about the start point, only the target value.
Here’s what it looks like to Lerp an Audio Source’s volume:
Audio Sources are easy to fade as their 0-1 volume scale creates an even linear fade.
However, if you’ve followed any of my other posts or videos, you may already know that the same is not true when fading an Audio Mixer Group (including when making a volume control slider) which takes a bit of extra work to do properly.
Using an asset to Lerp (e.g. DOTween Pro)
Hopefully, I’ve shown that using Lerp to animate and move objects can be easy.
But, it can be even easier than that.
There are a number of Unity assets available that provide code-free alternatives to writing your own Lerp scripts.
DOTween Pro, for example, which is probably the most popular and fully-featured, provides a simple, inspector-based component to easily add animation and movement to objects.
Essentially, it does everything you’ve read about in this post (plus a whole lot more) from a component in the inspector.
But is it worth it? Or is it easier to write your own scripts?
I wanted to find out.
Keep in mind that, while researching for this article, I’ve been writing Lerp scripts for days.
As someone who used to forget how to use Lerp and had to look it up every time, I’ll probably never be more familiar with it than I am right now, writing this.
Despite my unfair advantage…
I still got much faster results when using DOTween Pro.
DOTween makes Lerp-style animations easier and much, much faster.
Getting the object moving, fading, or rotating was extremely fast, I could preview it from the editor, and it was easy to get the results I wanted without ever opening a script.
Beyond this, there are also a huge number of easing options, path animation and options to connect with other scripts, objects or UI events.
So would I use it?
For a simple, one-off animation, I’d probably just write a simple script.
Or, more likely, I’d copy one of the examples above and change the values.
For anything larger than a small project, if I’m likely to be using Lerp over and over again, and especially if I want to create complex, chained animation and movements, I’d be much better off using DOTween Pro.
Even if I only used it to create animations that I could write manually, the amount of time I’m likely to save will easily outweigh the cost.
And that’s ignoring the other, more advanced features, which would be extremely difficult for me to recreate manually.
So, I’ll definitely be using it again and I definitely recommend it.
Now I want to hear from you
Are you using Lerp to create animation or movement in your project?
How are you using it? And have you been using any unconventional methods to get the effect you want?
Or maybe you’ve got a great tip for using Lerp that others would love to know?
Whatever it is, let me know by leaving a comment.
by John Leonard French
Game audio professional and a keen amateur developer.
Get Game Development Tips, Straight to Your inbox
Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.
My favourite time-saving Unity assets
Rewired (the best input management system)
Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.
DOTween Pro (should be built into Unity)
An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.
Easy Save (there’s no reason not to use it)
Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.