I am trying to make/edit a script to play music in certain areas. It works fine when you’re walking around normally and stuff. However, if your avatar tilts while in the area, like if you went in the water for example, the audio stops. I’m not great at scripting but I believe it’s because since it’s using ray casting, it’s shooting ‘invisible rays’ out the bottom of the humanoid root part, and once that ray hits a certain brick under the player, it starts playing music until it no longer hits that certain brick. I think the problem is when the avatar tilts, the ray is shooting off into the horizon and just barely missing the brick under the player. I’m not great at coding so I could be completely wrong but that’s just what I think. What I’ve tried is making it so the ray would ALWAYS shoot downwards no matter which direction your avatar is tilting by rotating where the ray cast comes out of, but since I have not much experience in coding, I was unable to do that and just put the code back into its original state. Also, I got this script off of YouTube by HowToRoblox, I did not make it.
local sound = Instance.new("Sound", script)
sound.Looped = true
local char = script.Parent
local hrp = char:WaitForChild("HumanoidRootPart")
local areasGroup = workspace:WaitForChild("Areas")
local currentArea = nil
local direction = -1000
game:GetService("RunService").Heartbeat:Connect(function()
local raycast = Ray.new(hrp.Position, hrp.CFrame.UpVector * direction)
local part = workspace:FindPartOnRayWithWhitelist(raycast, {areasGroup})
if part and part.Parent == areasGroup then
if part ~= currentArea then
currentArea = part
sound.SoundId = currentArea.Music.SoundId
sound:Play()
end
else
currentArea = nil
sound:Stop()
end
end)