Time for my question that I will likely figure out the stupid answer to right after I post it. 😆

I am making an ambient sound event that will increase in volume the closer the player gets to it. I figure out where the player is, do the math for where the event is, and go from there. Got it coded and working.... in the wrong direction. I am sure I am missing something obvious here. (I am using abs to make positive values) The tree to the event is simple enough: area 2d with a collision shape 2d and an audio stream player. Oh, and if the player hits the area, it goes to max (assigned) volume.

In a nutshell: the farther the player is, the quieter the sound should be. (I also have minimum and maximum levels as barriers to prevent weird spiking/nadirs.)

Sorry for posting longer code here - I need a fresh set of eyes.

extends Area2D


var _minVolume = -24.0
var _maxVolume = 6.0
onready var _sound = $AudioStreamPlayer2D
 
func _ready():
	_sound.volume_db = _minVolume
	
	
func _process(_delta):
	var _currentVolume = _sound.volume_db
	var _player = get_parent().get_node("Lydia")
	var _playerDistance = _player.global_position.x
	var _soundPosition = self.global_position.x
	var _sumDistance = abs((_soundPosition - _playerDistance)/16)
	
	if _playerDistance == _soundPosition:
		_sound.volume_db = _maxVolume
	if _playerDistance != _soundPosition:
		_sound.volume_db = -24.0+(_sumDistance)


	if _currentVolume > _maxVolume:
		_sound.volume_db = _maxVolume
	if _currentVolume < _minVolume:
		_sound.volume_db = _minVolume
  • I figured it out. I was subtracting from the wrong value for volume!
    Should have been subtracting from the MAX possible volume, not the minimum. Leaving it here for who needs it:

    	if _playerDistance != _soundPosition: ## subtract max volume by distance
    		_sound.volume_db = _maxVolume-(_sumDistance)
SnapCracklins changed the title to Ambient sound changing volume as player moves (SOLVED) .

I figured it out. I was subtracting from the wrong value for volume!
Should have been subtracting from the MAX possible volume, not the minimum. Leaving it here for who needs it:

	if _playerDistance != _soundPosition: ## subtract max volume by distance
		_sound.volume_db = _maxVolume-(_sumDistance)
a year later

Hey really impressive problem solving here. Good job!

I'm trying to implement this myself and I keep getting an Invalid operands 'float' and 'Vector2' in operator '-' error on the "_sound.volume_db = maxVolume-(sumDistance)" line. Is there a way you were converting the _sumDistance into a usable format for subtracting?

    rannsaka converting the _sumDistance into a usable format for subtracting

    In the post above that uses that value, it's using the X-coordinate of the Vector2, which is a float. Or you could use the length of the Vector2, which is also a float.