Skip to content

Instantly share code, notes, and snippets.

@Nimblz
Last active October 2, 2019 18:31
Show Gist options
  • Save Nimblz/5199394cbf0194519601f042f19d7b49 to your computer and use it in GitHub Desktop.
Save Nimblz/5199394cbf0194519601f042f19d7b49 to your computer and use it in GitHub Desktop.
Interpolation function for Roblox NumberSequence objects
local errors = {
incompatibleSequences = "Passed origin and goal NumberSequences do not have the same number of keypoints. Origin: $d Goal: $d",
}
-- double iter accepts two tables and the previous index and returns a new index and two values
local function doubleIter (tables, iterState)
iterState = iterState + 1
local valueOne = tables[1][iterState]
local valueTwo = tables[2][iterState]
if valueOne and valueTwo then
return iterState, valueOne, valueTwo
end
end
-- iipairs takes two tables and returns an iterator that iterates over both at the same time
local function iipairs (a,b)
return doubleIter, {a,b}, 0
end
-- lerp takes two values and a percent and returns a new value that percent inbetween origin and goal
local function lerp(origin,goal,alpha)
return origin + ((goal-origin) * alpha)
end
-- lerpNumberSequence
-- this function takes two number sequences and an alpha value and
-- returns a new number sequence that is blended between the two.
-- both passed sequences must contain the same number of keyframes.
local function lerpNumberSequence(originSequence, goalSequence, alpha)
local originKeypoints = originSequence.Keypoints
local goalKeypoints = goalSequence.Keypoints
local originSize = #originKeypoints
local goalSize = #goalKeypoints
-- confirm keyframe count is identical
assert(originSize == goalSize,
errors.incompatibleSequences:format(originSize, goalSize)
)
local interpolatedKeyframes = {}
for
index,
originKeypoint,
goalKeypoint
in iipairs(originKeypoints, goalKeypoints) do
local lerpedTime = lerp(originKeypoint.Time, goalKeypoint.Time, alpha)
local lerpedValue = lerp(originKeypoint.Value, goalKeypoint.Value, alpha)
local lerpedEnvelope = lerp(originKeypoint.Envelope, goalKeypoint.Envelope, alpha)
interpolatedKeyframes[index] = NumberSequenceKeypoint.new(lerpedTime,lerpedValue,lerpedEnvelope)
end
return NumberSequence.new(interpolatedKeyframes)
end
return lerpNumberSequence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment