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.
How to make audio play only when the player is in a specific area?
1 answer
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)
This discussion is preserved as it was. New answers, comments, and votes are closed.
