If you are doing this on the client (so it doesn’t update on the server and only player sees the changes), you could just use TweenService
for all of this, if instead you need animation to play on the server its best to use the script above and just have another loop incrementing the attachments back.
If you play animation on the client:
local ts = game:GetService("TweenService")
local info = TweenInfo.new(
20, --time it takes for it to finish
Enum.EasingStyle.Linear, --linear makes it move at the same speed entire time
Enum.EasingDirection.Out, --easing direction of the tween
-1, --how many times to repeat (-1 makes it repeat forever)
true --if it reverses (when it reaches the end it goes back to start)
)
ts:Create(attachment,info,{CFrame = CFrame.new(0, 0, -76.758)}):Play()
This way however it will take same amount of time to go back and forth.
If you want it to take less time going back you would create 2 tweens:
while true do
ts:Create(attachment,TweenInfo.new(20),{CFrame = CFrame.new(0, 0, -76.758)}):Play()
task.wait(20)
ts:Create(attachment,TweenInfo.new(10),{CFrame = CFrame.new(0, 0, -78.758)}):Play()
task.wait(10)
end
Keep in mind that tweens dont yield the script, so you need to add a wait after starting the tween.
If you want to animate it on the server instead you would just need to add another while loop to reverse the movement:
cumulative = 0 --reset the total so we can start again
while cumulative < final do --loop for amount of time specified
cumulative += run.Heartbeat:Wait() --add amount of time between frames
attachment.CFrame = CFrame.new(0, 0, -76.758 - cumulative * 0.1) --set cframe to current total * 0.1
end
You would just do this instead of resetting it. If you want it to take less amount of time you would just create another final
variable, lets say final2 = 10
, replace cumulative < final
with cumulative < final2
and change 0.1
to 0.2
(in this case 0.2 is enough as 10 * 0.2 = 2, but if you want it to move even faster you would need to calculate it depending on how long you want it to take by doing distance/time
distance being 2 studs in this case and time 10 seconds).