Per
request, here's a simple piece of code that (sort of) works for me:
-- LUA Script - precede every function and global member with lowercase name of script + '_main'
-- Sound volume is relative to player distance
SndPlaying = SndPlaying or {}
function soundvolume_init(e)
SndPlaying[e] = false;
end
function soundvolume_main(e)
local TriggerDist = 500;
-- do not edit below this line
local PlayerDX = g_Entity[e]['x'] - g_PlayerPosX;
local PlayerDY = g_Entity[e]['y'] - g_PlayerPosY;
local PlayerDZ = g_Entity[e]['z'] - g_PlayerPosZ;
local PlayerDist = math.sqrt(math.abs(PlayerDX*PlayerDX)+math.abs(PlayerDY*PlayerDY)+math.abs(PlayerDZ*PlayerDZ));
if PlayerDist < TriggerDist then
local percent = math.floor((PlayerDist/TriggerDist) * 100);
local volume = 100 - percent;
if not SndPlaying[e] then
LoopSound(e, 0); -- or PlaySound(e, 0);
SndPlaying[e] = true;
end
SetSoundVolume(math.min(volume, 100));
Prompt('Volume is at '..volume..'%'); -- remove this line to hide volume information
else
StopSound(e, 0);
SndPlaying[e] = false;
end
end
How to use?
1) Place your entity on the map
2) Assign this script (soundvolume.lua) as it's main script
3) Change
TriggerDist variable to suit your needs. It's the distance at which the sound will start and will have lowest volume
4) Assign your sound to entity's Sound0 property
How it works?
It simply gets your distance from entity and calculate it as a percentage related to
TriggerDist. So if
TriggerDist is 500 and player is 500 units away, then it's 100%, if 400 it's 80%, 300 is 60%, 200 is 40%, 100 is 20% and so on...
Once we have this percentage, we simply set volume to
100 - our_percentage, so as we approach the entity the volume gets higher and when we get away it goes down.
However, there are two problems with this one:
1) I can't hear anything below 60% on my machine. Guess it's either FPSC:R problem or problem related to my sound card. Can someone check this pls?
2) The volume never reaches 100% with some entities as you can't get within distance of 0 because of their thickness. This probably could be improved if we could get entity thickness or hardcode the difference in the script. Or use entity without collision (and hidden?)
edit: It seems that FPSC:R doesn't check if the sound is already playing so I had to introduce global SndPlaying to store state of sound for each entity. WIthout this check I could hear only noise just like it's playing audio file from start over and over really fast.