So I'm trying to edit a simple humanoid finding script so it will play a sound when the humanoid is in distance, but stop the sound when the humanoid is out of distance, and then play it again when the humanoid comes back into the range of the enemy. I'm having some trouble with this because I'm not really an amazing scripter and people keep asking for a better AI in my game.. Can someone please assist me? Thanks! Here's the script:
local AI = script.Parent local AIName = AI.Name local AItorso = AI.Torso local list = game.Workspace:children() local torso = nil local dist = 40 -- Area to search local temp = nil local human = nil local temp2 = nil for x = 1, #list do temp2 = list[x] if temp2.className == "Model" then temp = temp2:findFirstChild("Torso") if temp ~= nil then human = temp2:findFirstChild("Humanoid") if human ~= nil and (human.Health > 0) and (temp2.Name ~= AIName) then -- not named the same as us. script.Parent.Sound:Play() end -- closer? end -- human? Not us. end -- Has torso? end -- Model?
Here is what I did to make it work:
local part1 = game.Workspace.AI.Torso --The torso of your AI local player = game.Players.LocalPlayer --Gets the player local part2 = game.Workspace:WaitForChild(player.Name):WaitForChild("HumanoidRootPart") --The player local Sound = game.Lighting.Sound --Your Sound, place in PlayerGui for local sound instead of global while true do local magnitude = (part1.Position - part2.Position).magnitude if magnitude < 50 then if not Sound.IsPlaying then Sound:Play() end elseif magnitude >= 50 then if Sound.IsPlaying then Sound:Stop() end end wait(0.01) end
If this helped you out, make sure you accept the answer!
Use the magnitude between the center point of the sound and the humanoid's torso.
local mag = (Torso.Position - Center.Position).magnitude if mag < 50 then if not Sound.IsPlaying then Sound:Play() end elseif mag >= 50 then if Sound.IsPlaying then Sound:Stop() end end