So I have rigged a door and animated it so that the doors will open automatically when a player is nearby.
I have tried various ways of detecting when a player is nearby, Touched and TouchEnded, Region3, and Magnitude, all have seemed to make the door animation play repeatedly even when using debounce.
local doorOpen = false
local OpenAnimation = script.Parent.Parent.Open
local CloseAnimation = script.Parent.Parent.Close
while wait(0.1) do
local players = game.Players
for i, v in pairs(players:GetChildren()) do
if v.Character and not doorOpen then
doorOpen = true
local mag = (script.Parent.Position - v.Character.PrimaryPart.Position).Magnitude
if mag < 20 then
local LoadOpenAnimation = script.Parent.Parent.AnimationController:LoadAnimation(OpenAnimation)
LoadOpenAnimation:Play()
elseif mag > 20 and plr then
plr = nil
local LoadCloseAnimation = script.Parent.Parent.AnimationController:LoadAnimation(CloseAnimation)
LoadCloseAnimation:Play()
doorOpen = false
end
end
end
local doorOpen = false
local OpenAnimation = script.Parent.Parent.Open
local CloseAnimation = script.Parent.Parent.Close
local players = game.Players
local door = workspace:WaitForChild("Door") --change this reference
door.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local player = players:GetPlayerFromCharacter(hit.Parent)
if not doorOpen then
local mag = (script.Parent.Position - v.Character.PrimaryPart.Position).Magnitude
if mag <= 20 then
local LoadOpenAnimation = script.Parent.Parent.AnimationController:LoadAnimation(OpenAnimation)
LoadOpenAnimation:Play()
doorOpen = true
elseif mag >= 20 then
local LoadCloseAnimation = script.Parent.Parent.AnimationController:LoadAnimation(CloseAnimation)
LoadCloseAnimation:Play()
doorOpen = false
end
task.wait(5) --5 seconds between opening door again
doorOpen = false
elseif doorOpen then
--do code when door is open if needed
end
end
end)