How would I go about making it so that when the player is within the trigger a sound is played X distance behind the player? This next bit may be difficult; the particular part I want to include this in, is in a level that takes place in long streets. Is there any way to make it so that the sound is only played behind the player but within the confines of the street?
The only way i can think to do so is to attach the sound to an invisible NPC that follows the player but cannot go through walls. Would that work?
The “invisible NPC” alternative may cause problems with shots, explosions or other moving objects because the NPC collider will block them.
If the trigger is static, you can use its position/orientation to define the sound origin, and play the sound at that point with AudioSource.PlayClipAtPoint: this function creates a temporary game object with an AudioSource at the specified point, plays the sound and destroys the object automatically. The trigger volume orientation will define the sound direction: if the player enters its front side, the trigger’s forward direction will be used; if entering the back side, use the backward direction (trigger script):
var sound: AudioClip;
var distance: float = 30;
function OnTriggerEnter(other: Collider){
if (other.tag == "Player"){
var tPlayer = other.transform;
// find the direction trigger->player:
var dirPlayer = tPlayer.position - transform.position;
// get the absolute angle from the trigger forward direction:
var angle = Vector3.Angle(dirPlayer, transform.forward);
if (angle < 90){
dirPlayer = transform.forward; // player in front of the trigger
} else {
dirPlayer = -transform.forward; // player behind the trigger
}
// calculate the point at "distance" behind the player:
var point = tPlayer.position + dirPlayer * distance;
AudioSource.PlayClipAtPoint(sound, point);
}
}
Another possibility is to define the sound origin using the player’s forward direction, then check if there are no obstacles in between with Linecast (trigger script):
var sound: AudioClip;
var distance: float = 30;
function OnTriggerEnter(other: Collider){
if (other.tag == "Player"){
var tPlayer = other.transform;
// calculate the point at "distance" behind the player:
var point = tPlayer.position - tPlayer.forward * distance;
// check if there are no obstacles in between:
if (!Physics.Linecast(tPlayer.position, point)){
// free line of sight: play the sound there:
AudioSource.PlayClipAtPoint(sound, point);
}
}
}