Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make this player finding script play sounds properly?

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? 


2 answers

✓ Accepted answer

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

1 comment

0

Tbh I'm very confused as to what you are defining in this script. What do you mean by the center point of the sound? Who's humanoid's torso? The player's or the enemy's?

This discussion is preserved as it was. New answers, comments, and votes are closed.