campfire/Assets/Scripts/AmbientSoundGenerator.cs

57 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AmbientSoundGenerator : MonoBehaviour {
public GameObject AmbientSfxPrefab;
public float MinDistance;
public float MaxDistance;
public AudioClip[] Clips;
[Header("Cooldown configuration")]
public float MinCooldown;
public float MaxCooldown;
public int TooManySoundsCount;
[Tooltip("")]
public float TrackingDuration;
[Header("Runtime values")]
public float AmbientNoiseCooldown = 0f;
private Transform World;
private List<float> SoundTimes = new List<float>();
private void Awake() {
World = GameObject.FindGameObjectWithTag("World").transform;
}
private void Update() {
AmbientNoiseCooldown -= Time.deltaTime;
if (AmbientNoiseCooldown <= 0) {
AmbientNoiseCooldown += Random.Range(MinCooldown, MaxCooldown) + TrackingDuration * Mathf.Pow(SoundTimes.Count / TooManySoundsCount, 2);
int RemoveUntil = -1;
for (int I = 0; I < SoundTimes.Count; I++) {
if (Time.time - SoundTimes[I] > TrackingDuration) {
RemoveUntil = I;
} else {
break;
}
}
SoundTimes.RemoveRange(0, RemoveUntil + 1);
SoundTimes.Add(Time.time);
float Distance = Random.Range(MinDistance, MaxDistance);
float Rads = Random.Range(0, 2 * Mathf.PI);
Vector3 Offset = new Vector3(Mathf.Cos(Rads) * Distance, Random.Range(0f, 5f), Mathf.Sin(Rads) * Distance);
GameObject Obj = Instantiate(AmbientSfxPrefab, transform.position + Offset, new Quaternion(), World);
AudioSource Sfx = Obj.GetComponent<AudioSource>();
if (Sfx != null) {
Sfx.clip = Clips[Random.Range(0, Clips.Length)];
Sfx.volume = Mathf.Sqrt(Random.Range(0.3f, 1f));
Sfx.Play();
}
}
}
}