How do I detect if player has left the zone/area?

The script below doesn’t see a player leaving the area.

local player = game.Players.LocalPlayer or game.Players.PlayerAdded:Wait()
local gui = script.Parent.Parent
local area = workspace.Ambient.Area
local TweenService = game:GetService("TweenService")
local Info = TweenInfo.new(1,Enum.EasingStyle.Quad,Enum.EasingDirection.InOut)
local do1 = TweenService:Create(gui.Frame,Info,{Position = UDim2.new(0, 877,0.221, 0)}) --{0, 877},{0.221, 0}
local do2 = TweenService:Create(gui.Frame,Info,{Position = UDim2.new(1, 0,0.221, 0)})

local debounce = false

area.Touched:Connect(function(touch)
	if not touch.Parent:FindFirstChild("Humanoid") then return end
	if debounce == true then return end
	debounce = true
	local char = touch.Parent
	local plr = game.Players:GetPlayerFromCharacter(char)
	do1:Play()
	
	if not touch then
		do2:Play()
		wait(1.2)
		debounce = false
	end
end)

I tried to look into the internet but I did not find much information here. This was supposed to be a selected GUI area, but as of right now I am struggling to fix it. If there is anything I missed or skipped, please let me know. Thanks.

you can make an area all around the zone that if touched tells that the player has left the zone

1 Like

I’ll try. Thanks for the feedback.

1 Like

workspace:GetPartsInPart(area)

then

for i, part in pairs(workspace:GetPartsInPart(area)) do
end

then

local isInArea = false
for i, part in pairs(workspace:GetPartsInPart(area)) do -- iterate throught each part
   if part = char.HumanoidRootPart then -- check for character
      isInArea = true
      break -- leave the cycle
   end
end

if isInArea = false then -- if character still not founded, then
    -- zone leave code here
end

final code:

area.Touched:Connect(function(touch)
	if not touch.Parent:FindFirstChild("Humanoid") then return end
	if debounce == true then return end
	debounce = true
	local char = touch.Parent
	local plr = game.Players:GetPlayerFromCharacter(char)
	do1:Play()
	
	if not touch then
		do2:Play()
		wait(1.2)
		debounce = false
	end

    repeat
       local isInArea = false
       for i, part in pairs(workspace:GetPartsInPart(area)) do -- iterate throught each part
          if part = char.HumanoidRootPart then -- check for character
             isInArea = true
             break -- leave the cycle
          end
       end

       if isInArea = false then -- if character not founded, then
          -- zone leave code here
          break -- leave loop
       end

       task.wait(1)

    until false
end)

1 Like

updated code

You could define regions, and then check what region players are in. This can be done with region3

1 Like

If you’re planning to use .Touched for the zone, then use .TouchEnded for when the character walks out