I want my script to detect if a player is in a zone while leaving, to subtract a number in the NumberValue.
Currently, I have been trying to detect that, but every time it doesn’t seem to be able to detect that.
I don’t think I found any specific topic about what I’m describing here, I have tried looking for “HumanoidRootPart” inside of the zone for the leaving function “PlayerRemoving”, but it wouldn’t work.
local NumberValue = script.Parent.PlayerCount
local counter = script.Parent:WaitForChild("Counter")
local function onTouch(part)
wait()
if (part.Name ~= "HumanoidRootPart") then return end
local character = part.Parent
NumberValue.Value = NumberValue.Value + 1
counter.BillboardGui.TextLabel.Text = tostring(NumberValue.Value)
end
local function onTouchEnded(part)
wait()
if (part.Name ~= "HumanoidRootPart") then return end
local character = part.Parent
NumberValue.Value = NumberValue.Value - 1
counter.BillboardGui.TextLabel.Text = tostring(NumberValue.Value)
end
script.Parent.TouchEnded:Connect(onTouchEnded)
script.Parent.Touched:Connect(onTouch)
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(onTouchEnded)
end)
If the zone is a square, you take the positions of the corners, and the last known position of the player. This does mean you’ll need to track every player’s position, constantly.
Then, you check if the players position is in between those 2 corners. If yes, they were in the zone. If no, they were not.
If your zone is a circle, you take the center of the circle, and you check if the magnitude from the player to the center is larger than the radius. If it is not, they were inside the zone.
local i = 0
local playerPositions = {}
local getAllPositions = function()
for i, player in game.Players:GetChildren() do
if player.Character ~= nil and player.Character:FindFirstChild("HumanoidRootPart") ~= nil then
playerPositions[player]=player.Character.HumanoidRootPart.Position
end
end
print(playerPositions)
end
local zone = workspace.RedZone
local function isPositionInsideZone(position, zoneMin, zoneMax)
return position.x >= zoneMin.x and position.y >= zoneMin.y and position.z >= zoneMin.z and
position.x <= zoneMax.x and position.y <= zoneMax.y and position.z <= zoneMax.z
end
local function checkPlayerPosition(plr)
local lastPos = playerPositions[plr]
if lastPos then
local zone = workspace.RedZone
local zoneMin, zoneMax = zone.Position - zone.Size / 2, zone.Position + zone.Size / 2
if isPositionInsideZone(lastPos, zoneMin, zoneMax) then
print(plr.Name .. "'s last position is inside the zone.")
else
print(plr.Name .. "'s last position is outside the zone.")
end
end
end
game.Players.PlayerRemoving:Connect(function(plr)
local lastPos = playerPositions[plr]
if lastPos then
checkPlayerPosition(plr)
end
end)
while wait(1) do
i+=1
--l.transform(Vector3.new(i,50,0))
getAllPositions()
--checkPlayerPosition(game.Players:GetChildren()[1])
end