How to move a part using lerp


  • So, you want to 'tween' a part?

    The answer is :lerp().

    :lerp() is a method found in Vector2, Vector3, Color3, and CFrame values. The following parameters are used when calling it:

    • value1 - The first value to use, it is what you call the method on
    • value2 - The second value to use
    • alpha - The position between these two values to return (number from 0-1 that can be a decimal)

    It is used to return the defined position (the alpha) inside the two given instances of the value type (value1 and value2).

    To explain this in more simple terms, if I have the numbers 0 and 2, and the alpha was 0.5, the method would return 1 (this won't actually work because lerp is not available for numbers). If the alpha was 1, it would return 2 - and if it was 0, it would return 1.


    Example:

    local vector1, vector2 = Vector3.new(0,0,0), Vector3.new(0,2,0)
    local position = 0.5
    local newVector = vector1:lerp(vector2,position)
    

    newVector would be equal to Vector3.new(0,1,0), since 0.5*2 is 1


    Now that we have lerp down, next comes on how we actually move the part.

    local part = script.Parent
    local startPosition = part.Position
    local desiredPosition = Vector3.new(10,10,0)
    
    for i = 0,1,0.005 do
    part.Position = startPosition:lerp(desiredPosition,i)
    wait()
    end
    

    Firstly, you set the start and desired positions as values (make sure the start position does not change!).
    Next, you setup the for loop. You can use lerp anywhere, but I'm using the for loop because of its simplicity.

    The for loop iterates 200 times (the number used as the step is 1/howeverManyTimesYouWantItToMove, which in this case is 0.005), and when it reaches the 200th iteration (AKA 1), the part will be at the desiredPosition.

    It then waits() for a very short time - the default wait time, because of how many iterations there are (because you don't want to wait 200 seconds for it to reach it's target, do you?)


    There you go, you're part is now moving smoothly (or at least as smooth as you made it)!

    If you have any questions or comments, please ask/say them below.

    Good luck on your scripting journey :smile: ~TDP


  • It also works with UDim2 values, I noticed.


  • @OldPalHappy I usually prefer to use ROBLOX's built-in tweening functions for UDim2 values unless I have a specific reason for using lerp, although it's nice to have the option there.


  • @Spongocardo Same, I find tweening for UDim2's easier then using Lerp. Although it is an option.


  • @Spongocardo Lerp is good for curves, from my experience. Otherwise tweening is the way to go.

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.