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

How to make audio play only when the player is in a specific area?

Asked by 8 years ago

I don't mean 3D Sound. I mean something like the player enters a building and music specific to that building plays. Once the player walks out, the music stops. Something like Work at a Pizza Place.

1 answer

Log in to vote
0
Answered by
Link150 1355 Badge of Merit Moderation Voter
8 years ago

You could check whether the character's torso is inside a bounding box delimited by two Vector3 values.

Another solution, especially useful if you plan on building complex shaped houses would be to have two invisible bricks serve as a "doors" and have a script inside both of them to listen for the "Part.Touched" event. If the inside brick is touched then the music triggers. If the outside brick is touched then the music stops. Note that the music would still persist for example if the player teleported out. Maybe combining the two solutions could solve this problem. I'll leave this to you as an exercise.

For the sake of simplicity, let's stick to the second solution.

Inside brick:

local player = game.Players.LocalPlayer
local character = player.Character

local part = script.Parent


local function onTouched(hit)
    if hit.Parent == character then
        -- I think having the sound in the local player's instance will
        -- only have it play for him but I am not entirely sure about this.
        local sound = player:FindFirstChild("Sound") or Instance.new("Sound", player)

        -- Replace the sound's assetId with that of your own music.
        sound.SoundId = "https://www.roblox.com/?id=138103237"
        sound.Looped = true

        -- If the character dies or resets then we stop the music as
        -- he respawns.
        character.onCharacterAdded:connect(function()
            sound:Stop()
            sound:Destroy()
        end)

        sound:Play()
    end
end


part.Touched:connect(onTouched)

Outside brick:

local player = game.Players.LocalPlayer
local character = player.Character

local part = script.Parent


local function onTouched(hit)
    if hit.Parent == character then
        local sound = player:FindFirstChild("Sound")

        -- We check if there was indeed a sound playing.
        if sound then
            sound:Stop()
            sound:Destroy()
        end
    end
end


part.Touched:connect(onTouched)
Ad

Answer this question