How to check when player has moved away to reverse an Animation?

Hello, I am trying to code a chest vendor that opens when a player clicks it but if they walk away it closes, everything works perfectly except for the animation I am trying to have reverse itself when the player is 15 studs away.

Is there a better method to determine when a player is a certain distance away to resume the animation into a closing position or should I re-work the animation to open then close in the same animation instead of reversing it?

local ac = v.AnimationController
		local anim
		anim = ac:LoadAnimation(script.WepOpen)	
		
		v.WepButton.ClickDetector.MouseClick:Connect(function(plr)
			
			--[[local hum = plr.Parent:FindFirstChild("Humanoid")
			if not hum then return end
			local plr = game.Players:GetPlayerFromCharacter(hum.Parent)
			if not plr then return end]]
			
			local kfc
			kfc = anim.KeyframeReached:connect(function(kf) -- Animations
			if kf == "Open" then			
			anim:AdjustSpeed(0)
					
			local ch = plr.Character
			local lowerTorso = ch:FindFirstChild("LowerTorso")
			if (lowerTorso.Position-v.WepButton.Position).magnitude > 15 then
			anim:AdjustSpeed(-1)
					end
				end
			end)
			
			anim:Play()

https://gyazo.com/df8f5780de20d684aaf5970b20a3d9fa

This code only checks if the player is 15 studs away once.

if (lowerTorso.Position-v.WepButton.Position).magnitude > 15 then
    anim:AdjustSpeed(-1)
end

So you should place it in a loop so it constantly checks if the player is away.

coroutine.wrap(function()
   while wait(1) do
       if (lowerTorso.Position-v.WepButton.Position).magnitude > 15 then
		anim:AdjustSpeed(-1)
        anim:Play(0.100000001, 1, -1) -- check below
        break
       end
   end
end)()

Check this out by the way.

Also I suggest automatically closing the chest and break the loop after some time even if the player is close to stop it from looping forever.

1 Like