I'm using a player's HumanoidRootPart to see if they are within a given 'zone' to play a certain sound based on whether they are within that zone, or outside of it.
The 'zone' is just an invisible Part that has CanCollide set to false.
I have this script setup that somewhat works:
local Player = game:GetService("Players").LocalPlayer local HumanoidRootPart local Humanoid function Check() local Result = HumanoidRootPart.Touched:Wait() if Result.Name == "IndoorArea" then return true else return false end end Player.CharacterAdded:Connect(function(Character) HumanoidRootPart = Character:WaitForChild("HumanoidRootPart") Humanoid = Character:WaitForChild("Humanoid") while Humanoid.Health > 0 and Humanoid.Health ~= 0 do if Check() == true then print("In zone") else print("Outside zone") end wait() end end)
(This script is located within StarterPlayerScripts, and is a local script)
This script works, but it sometimes detects that the player is outside the zone even when they are inside the zone and vice versa.
If anyone know how I can fix this script or a different method that is more viable than this one, help is much appreciated.
Thanks!
You could do this with a boolean variable.
local function onPartTouched(touched) local player = game:GetService("Players"):GetPlayerFromCharacter(touched.Parent) if player and touched.Name == "HumanoidRootPart" then --code end end local function onPartTouchEnded(touched) local player = game:GetService("Players"):GetPlayerFromCharacter(touched.Parent) if player and touched.Name == "HumanoidRootPart" then --code end end part.TouchEnded:Connect(onPartTouchEnded) part.Touched:Connect(onPartTouched)
local distance = 50 while wait(0.01) do if (game.Workspace.Part.Position - game.Players.LocalPlayer.Character.HumanoidRootPart.Position).Magnitude > 50 then Sound:Play() else Sound:Stop() end end