How to use lerp to interpolate two values in a set duration of time?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ClumsyDog

Basically, I want to use the lerp() function and set it interpolate value a to value b in a certain amount of time instead of passing in a percentage. A formula to do this would be really helpful. I know something like this exists for tweens, but I don’t want to unnecessarily add another node to my tree if I can do it with lerp. Any help is appreciated.

:bust_in_silhouette: Reply From: Lopy

This is likely to break if you try to pause the game:

var start_time
var duration
var starting_value
var final_value

func start(d, a, b):
    start_time = OS.get_ticks_msec()
    duration = d
    starting_value = a
    final_value = b

func _process():
    var elapsed = OS.get_ticks_msec() - start_time
    if elapsed <= duration:
        lerp(starting_value, final_value, duration / elapsed)

A constant interpolation like that is likely to produce an ugly result, which is one of the reasons to use Tween. Node count is not an issue in most situations, as it only causes problems when it reaches around 5000. Even so, you should be able to use a single Tween to interpolate the properties of multiple objects at the same time.

Thanks a lot! Really clear, concise, and helpful answer. I’ll be sure to remember all that. Thanks for taking the time to help!

ClumsyDog | 2021-02-14 06:09

:bust_in_silhouette: Reply From: nonunknown

you can use Tween node which is just one/two lines of code:

var tween:Tween = Tween.new()
add_child(tween) #or in some cases call_deferred("add_child",tween)
tween.interpolate_property($Node2D, "position",
    Vector2(0, 0), Vector2(100, 100), 1,
    Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
tween.start()
tween.connect("tween_all_completed",tween,"queue_free") #in case you call tween only one time, this line tells the tween node to auto destroy.

Thanks! This is really helpful. Thanks for taking the time to help!

ClumsyDog | 2021-02-15 03:01