How to constantly update a member variable?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Kayd

So, I have a custom audio code on my tilemaps (for easy access to all child nodes) that calculates the distance between nodes and plays back sounds at particular levels. It is supposed to calculate the distance between the player and the event, and then calculate the playback level and pitch based on the distance.

Whenever I start up the game, however, it calculates the distance between the event and the player, but then doesn’t continuously update. I put this under “func _process(delta)” but that doesn’t continuously update the variable.

extends AudioStreamPlayer2D

var parent;
var player;

func _ready():
	parent = getParent();
	player = getParent().getParent().get_node("Player");
	pass
	
func soundLevel(vectorOne, vectorTwo):
     var distance = sqrt((((vectorTwo.x - vectorOne.x) * (vectorTwo.x - vectorOne.x)) + ((vectorTwo.y - vectorTwo.x) * (vectorTwo.y - vectorTwo.x))))
     var logfactor = distance/100;
     var levelfactor = (log((logfactor)/log(2)));  
     var decibels = (-1.6)*levelfactor;
     return decibels;
   
func _process(delta):
	 var playerPosition = player.get_position(); 
	 var EventPosition = parent.get_position();
	 volume_db = soundLevel(playerPosition, EventPosition);
	 pass

How to I get it to update?
Also, why isn’t there a “get_parent” function for AudioPlayer2d?

:bust_in_silhouette: Reply From: kidscancode

Note: I edited your post to fix the formatting. Please format your code when you post to make it readable.

There are many issues here:

  • You wrote getParent() - the method is get_parent(). Godot uses snake_case for method and member variable names.

  • The whole purpose of AudioStreamPlayer2D is to attenuate volume based on distance. If your goal is to do this yourself, you should probably use AudioStreamPlayer instead.

  • position is a member variable of all Node2D-derived nodes. There is no need to create a second variable called playerPosition to store it. You can just use volume_db = soundLevel(position, parent.position)

  • The distance between two vectors can be found with vectorOne.distance_to(VectorTwo). No need for all that Pythagoras…

  • pass doesn’t do anything - it’s a placeholder “do nothing” statement. Also, semicolons aren’t needed in GDScript, although they don’t hurt anything if they’re there.

Thank you! You’ve answered basically every question I could have had when coding this. It’s fairly obvious, but I am new to GD script so I really appreciate the help.

Kayd | 2019-01-21 19:50