So in my game, or project, I have a script that inserts an explosion wherever the player clicks, and plays an explosion sound. I know how to get the distance from the character from where the person clicked, but how would I convert the distance to the sound's volume, that can only be > 0 but < 1?
Here's a basic script that will help to demonstrate what I'm saying,
local plr = game:GetService("Players").LocalPlayer local mouse = plr:GetMouse() local char = plr.Character or plr.CharacterAdded:wait() local Torso = char:WaitForChild("Torso") local Sound = script:WaitForChild("Sound") mouse.Button1Down:connect(function() local Distance = (Torso.Position - mouse.Hit.p).Magnitude Sound.Volume = --I need help with this part Sound:Play() end)
However, a few of the problems I've come to are that,
The distance get's larger instead of shorter the farther the player clicks
I'm not sure how to make the lower number larger than the bigger number
And I suck at math
Thank You.
There are probably better ways of calculating this but this is what I got working:-
local plr = game:GetService("Players").LocalPlayer local mouse = plr:GetMouse() local char = plr.Character or plr.CharacterAdded:wait() local Torso = char:WaitForChild("Torso") local Sound = script:WaitForChild("Sound") local soundDecPerStud = 1 local maxSound = 1 mouse.Button1Down:connect(function() print("click") local Distance = math.floor((Torso.Position - mouse.Hit.p).Magnitude) --print(Distance) local vol = maxSound - (Distance * soundDecPerStud) / 100 -- calculate sound fade then take from maxSound if math.abs(vol) == vol then -- only use posative numbers Sound.Volume = vol Sound:Play() end end)
Hope this helps, comment if you need more info.
You're making this harder than it needs to be. All you have to do is insert a sound into the part where the explosion is occurring and play the sound. If the sound is played in a physical environment, ROBLOX automatically changes the volume based on your distance from where the sound is playing.
I hope this helps!
I'm well aware I'm answering my own question. I'm doing this so that maybe in the future, someone can look at this with the same problem.
kingdom5's answer seems to work, however this was my first solution,
local Distance = (Torso.Position - mouse.Hit.p).Magnitude local vol = ((1/Distance)*12) sound.Volume = vol sound:Play()
Obviously, X_2's answer was much more simple, and efficient. However, it's not quite what I wanted. However it's a great solution. I slightly better solution going off of X_2's would be to parent the sound to the explosion. There still seems to be a very annoying problem with this though. When doing this, the explosion sound still plays, meaning the sounds everlap. This could work if you simply complement the sound, but trying to change the sound seems to be a no go.
Thank you guys for the help!