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:
01 | local AI = script.Parent |
02 | local AIName = AI.Name |
03 | local AItorso = AI.Torso |
04 |
05 |
06 | local list = game.Workspace:children() |
07 | local torso = nil |
08 | local dist = 40 -- Area to search |
09 | local temp = nil |
10 | local human = nil |
11 | local temp 2 = nil |
12 | for x = 1 , #list do |
13 | temp 2 = list [ x ] |
14 | if temp 2. className = = "Model" then |
15 | temp = temp 2 :findFirstChild( "Torso" ) |
Here is what I did to make it work:
01 | local part 1 = game.Workspace.AI.Torso --The torso of your AI |
02 | local player = game.Players.LocalPlayer --Gets the player |
03 | local part 2 = game.Workspace:WaitForChild(player.Name):WaitForChild( "HumanoidRootPart" ) --The player |
04 | local Sound = game.Lighting.Sound --Your Sound, place in PlayerGui for local sound instead of global |
05 |
06 | while true do |
07 | local magnitude = (part 1. Position - part 2. Position).magnitude |
08 | if magnitude < 50 then |
09 | if not Sound.IsPlaying then |
10 | Sound:Play() |
11 | end |
12 | elseif magnitude > = 50 then |
13 | if Sound.IsPlaying then |
14 | Sound:Stop() |
15 | end |
16 | end |
17 | wait( 0.01 ) |
18 | 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.
01 | local mag = (Torso.Position - Center.Position).magnitude |
02 |
03 | if mag < 50 then |
04 | if not Sound.IsPlaying then |
05 | Sound:Play() |
06 | end |
07 | elseif mag > = 50 then |
08 | if Sound.IsPlaying then |
09 | Sound:Stop() |
10 | end |
11 | end |