How do i increase the pitch of an audio based on the proximity?

Godot Version

4.3

Question

so, i did a simple mechanic, a very long raycast originated from the eyes that if it touches an enemy collision box, a short beep sound plays, waits a second, and plays again until the raycast no longer touches the enemy.

the problem is that i want to do a function that increases the pitch of the beeping sound the closer i get to an enemy and decreases the further away i am.

long story short i couldn’t do that last one.

the following code i used is from a unity forum with the same problem

func play_beep():

if tracker_collider.is_colliding():

var colliding_body = tracker_collider.get_collision_normal()
var origin = tracker_collider.global_transform.origin
var distance = origin.distance_to(colliding_body)
var c = clamp(distance, 0.6, 1.3)
beeper.pitch_scale = c
beeper.play()

basically, it stucks in 0,6 pitch no matter how far i am from the enemy. any help would be appreciated!

Change your colliding_body to retrieve a collider instead of a normal.

And calculate your distance to the position of a colliding body.

Mind you that the pitch will only change within the distance of 0.6 to 1.2 units from the original distance, which is a rather small range.

ok, it worked, but i forgot to mention that in the original func in unity, the pitch is reversed, and now i have the same problem, i mean that the further away i am from the enemy, the higher the pitch and vice versa

i tried putting a minus in the distance variable but the pitch stucks in the middle clamp number

You can do something like that:

var min_pitch: float = 0.6
var max_pitch: float = 1.3
var difference: float = max_pitch - min_pitch
var c: float = min_pitch + smoothstep(min_pitch, max_pitch, distance) * difference
beeper.pitch_scale = c
beeper.play()
1 Like

ok, i tried this but as you have said earlier, the range was too short so i ended doing this:

func play_beep():
	if tracker_collider.is_colliding():
		var beep_min_pitch: float = 0.01
		var beep_max_pitch: float = 5
		var difference: float = beep_max_pitch - beep_min_pitch
		var colliding_body = tracker_collider.get_collider()
		var origin = tracker_collider.global_transform.origin
		var distance = origin.distance_to(colliding_body.global_position)
		var c: float = beep_min_pitch + smoothstep(beep_max_pitch, beep_min_pitch, distance/55) * difference
		beeper.pitch_scale = c / 6
		beeper.play()

even if it doesn’t work exactly how i pictured it on my mind, its good enough for me! really really thank you for helping me, i also learned that i have to read the docs lol. thanks for help!

1 Like