Hello! I have a loop in a script that increases/decreases a number value between a minimum/maximum amount, and the value does this without any issue. I am trying to find a way to smooth the amount of change towards the minimum/maximum ends, does anyone know how I can do this?
This is what I currently have without any smoothing:
local val = 1
local min = 0
local max = 100
local goingUp = true
while true do
wait()
if val < max and val > min then
if goingUp == true then
val = val + 1
else
val = val - 1
end
else
if goingUp == true then
goingUp = false
val = val - 1
else
goingUp = true
val = val + 1
end
end
end
for number = start, end, increment do
end
for variable = 1, 100 do -- Default is 1
print(number) -- will print 1 - 100
end
for i = 50, 25, -0.25 do
--Count from 50 to 25 in increments of -0.25
end
Thank you so much for trying to help, I should have further defined what I meant by “smoothing” though. I am trying to have the number slow down towards the max and minimum but remain relatively fast in the middle.
This is far more complicated, out of curiosity what are you using this for? Roblox has functionality built into Tweens that allow for nice phasing of parts using cubic interpolation.
local val = 1
local min = 0
local max = 100
local goingUp = true
local waitTime = 0.1
while true do
wait(waitTime)
if val >75 or val<25 then
waitTime = 0.2
else
waitTime = 0.1
end
if val < max and val > min then
if goingUp == true then
val = val + 1
else
val = val - 1
end
else
if goingUp == true then
goingUp = false
val = val - 1
else
goingUp = true
val = val + 1
end
end
end
You can add more if statements to make it even smoother, this is just to give you an idea
This solution won’t look the best, as it just changes the increment time, not how much is actually incremented. Yes it achieves the goal, but it will get stutter-y near the beginning and end.
It could be possible to generate a linear interpolation function to overlay onto something like a cubic curve…
function PhaseValue(startv, endv, increment, number)
for value = startv, endv, increment do
local t = -math.sqrt(4-math.pow(value, 2))+2
number = (1 - t) * startv + t * endv
task.wait()
end
end
local number = 0
PhaseValue(0, 100, 1, number)
function cubicBezier(t, p0, p1, p2, p3)
return (1 - t)^3*p0 + 3*(1 - t)^2*t*p1 + 3*(1 - t)*t^2*p2 + t^3*p3
end
function interpolateValue(startv, endv, steps, value)
for i = 0, 1, 1/steps do
value = cubicBezier(
i,
Vector2.new(0, startv),
Vector2.new(0.5, startv),
Vector2.new(0.5, endv),
Vector2.new(1, endv)
).Y
task.wait()
end
value = endv
end
local number = 0
interpolateValue(0, 100, 100, number)
You can play around with those two 0.5 values to increase the smoothness of the curve, so long as they add to 1 (ie change to 0, 0.25, 0.75, 1 in the Vector 2s for a smoother curve)