overextended / ox_lib

A FiveM resource and script library for Lua and JS.
https://overextended.dev/ox_lib
GNU Lesser General Public License v3.0
282 stars 378 forks source link

linear interpolation for vectors. #570

Closed Demigod916 closed 2 months ago

Demigod916 commented 2 months ago

math.lerpVectors is a standard linear interpolation between 2 vectors. This will allow developers to smoothy transition between 2 vectors for rotations or coords over a set duration.

this function is currently blocking. optional async is something that we can add if desired.

example:

RegisterCommand('testLerp', function(source, args, raw)
    lib.requestModel(`gr_prop_gr_target_04b`)

    local offset = GetOffsetFromEntityInWorldCoords(cache.ped, 0, 3.0, 0)
    local object = CreateObject(`gr_prop_gr_target_04b`, offset.x, offset.y, offset.z, false, false, false)

    PlaceObjectOnGroundProperly_2(object)
    math.lerpVectors(vec3(0, 0, 0), vec3(-90.0, 0, 0), 500, function(interpolated)
        SetEntityRotation(object, interpolated.x, interpolated.y, interpolated.z, 0, false)
    end)
end)

https://github.com/overextended/ox_lib/assets/60995067/3d1d06a7-4458-4f35-8519-be37a3a5f6f8

thelindat commented 2 months ago

An iterator might look a bit nicer in this situation.

for interpolated in math.lerpVectors(vec3(0, 0, 0), vec3(-90.0, 0, 0), 500) do
    SetEntityRotation(object, interpolated.x, interpolated.y, interpolated.z, 0, false)
end)

I would also prefer math.lerp that can handle interpolation of scalars, vectors, or even tables (both arrays and hashmaps, to a limit).

Demigod916 commented 2 months ago

so for the iterator method, it would use a coroutine?

thelindat commented 2 months ago

You basically just return a function instead of having a function argument; it calls the function until it gets a nil value.

Demigod916 commented 2 months ago

okay updated.

for value in math.lerp(0, 100, 500) do
    print(value)
end

for vec in math.lerp(vec3(0, 0, 0), vec3(10, 10, 10), 1000) do
    print(vec.x, vec.y, vec.z)
end

for tbl in math.lerp({x=0, y=0}, {x=10, y=20}, 1000) do
    print(tbl.x, tbl.y)
end