Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago

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

Log in to vote
3
Answered by
nanaluk01 247 Moderation Voter
7 years ago

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!

Ad
Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

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
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? ragingskull182 67 — 7y

Answer this question