--// SERVICES
local TweenService = game:GetService("TweenService")
--// FUNCTIONS
function LinearInterpolation(step, a, b)
if typeof(a) == "Instance" or typeof(b) == "Instance" then
local a = a.Position
local b = b.Position
return a * (1 - step) + b * step
elseif typeof(a) == "CFrame" or typeof(b) == "CFrame" then
return a:Lerp(b, step)
else
return a * (1 - step) + b * step
end
end
function GetStepPositionFromBezierCurve(step, pointsTable)
local CurrentLerpings = pointsTable
repeat
local NewLerpings = {}
for index, value in pairs(CurrentLerpings) do
if (#CurrentLerpings - 1) >= index then
NewLerpings[index] = LinearInterpolation(step, value, CurrentLerpings[index + 1])
end
end
CurrentLerpings = NewLerpings
until #CurrentLerpings == 1
return CurrentLerpings[1]
end
--// MODULE
local BezierCurvesModule = {}
--// MODULE FUNCTIONS
function BezierCurvesModule.PerformBezierCurve(part, duration, pointsTable)
if part and duration and pointsTable then
local StepValue = Instance.new("NumberValue", part)
StepValue.Name = "BezierCurveStepValue"
StepValue.Value = 0
local StepValueTween = TweenService:Create(StepValue, TweenInfo.new(
duration,
Enum.EasingStyle.Linear
), {
Value = 1
})
StepValueTween:Play()
StepValue.Changed:Connect(function(newValue)
local NewPartPosition = GetStepPositionFromBezierCurve(newValue, pointsTable)
part.Position = NewPartPosition
end)
StepValueTween.Completed:Connect(function()
StepValue:Destroy()
end)
else
error("[ERROR] Some arguments are missing in the function 'PerformBezierCurve'.")
end
end
function BezierCurvesModule.PerformBezierCurveWithTween(part, tweenTable, pointsTable)
if part and tweenTable and pointsTable then
local StepValue = Instance.new("NumberValue", part)
StepValue.Name = "BezierCurveStepValue"
StepValue.Value = 0
local PartTweenInfo = TweenInfo.new(
tweenTable.Information[1],
tweenTable.Information[2],
tweenTable.Information[3],
tweenTable.Information[4],
tweenTable.Information[5],
tweenTable.Information[6]
)
local PartTween = TweenService:Create(part, PartTweenInfo, tweenTable.Goals)
local StepValueTween = TweenService:Create(StepValue, PartTweenInfo, {
Value = 1
})
StepValueTween:Play()
PartTween:Play()
StepValue.Changed:Connect(function(newValue)
local NewPartPosition = GetStepPositionFromBezierCurve(newValue, pointsTable)
part.Position = NewPartPosition
end)
StepValueTween.Completed:Connect(function()
StepValue:Destroy()
end)
else
error("[ERROR] Some arguments are missing in the function 'PerformBezierCurveWithTween'.")
end
end
--// RETURNS
return BezierCurvesModule
1 Like
Your code is good in my opinion. I don’t think something needs a change. If I really wanted to “complain” about your code I would mention this:
local StepValue = Instance.new(NumberValue, part)|
StepValue.Name = BezierCurveStepValue|
StepValue.Value = 0 -- Default value of newly created NumberValues is 0. I think that putting this here is just a personal preference.
1 Like