campfire/Assets/Scripts/AmbientSoundGenerator.cs

76 lines
2.8 KiB
C#
Raw Normal View History

2020-04-20 20:46:48 +02:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
2020-06-12 21:28:40 +02:00
using UnityEngine.Rendering;
2020-04-20 20:46:48 +02:00
public class AmbientSoundGenerator : MonoBehaviour {
public GameObject AmbientSfxPrefab;
2020-04-20 22:20:32 +02:00
public AmbientEffect[] Effects;
public float Cooldown;
2020-04-20 20:46:48 +02:00
[Header("Runtime values")]
public float AmbientNoiseCooldown = 0f;
2020-04-20 22:20:32 +02:00
public float Roll = 0f;
2020-04-20 20:46:48 +02:00
private Transform World;
2020-04-20 22:20:32 +02:00
private float[] CumulativeChances;
private float TotalCumulativeChance;
private int[] RollsSince;
2020-04-20 20:46:48 +02:00
2020-06-12 21:28:40 +02:00
private void Update() {
// Initialize in Update, since in VR, we don't actually start in the right scene,
// because the player needs to be initialized in another scene,
// because the player persists over scene loads. Go figure.
if (World == null) {
GameObject WorldObject = GameObject.FindGameObjectWithTag("World");
if (WorldObject == null) {
// Not in the game scene.
return;
}
World = WorldObject.transform;
CumulativeChances = new float[Effects.Length];
TotalCumulativeChance = 0;
for (int I = 0; I < Effects.Length; I++) {
CumulativeChances[I] = TotalCumulativeChance;
TotalCumulativeChance += Effects[I].Chance;
}
RollsSince = new int[Effects.Length];
2020-04-20 22:20:32 +02:00
}
2020-04-20 20:46:48 +02:00
AmbientNoiseCooldown -= Time.deltaTime;
if (AmbientNoiseCooldown <= 0) {
2020-04-20 22:20:32 +02:00
AmbientNoiseCooldown += Cooldown;
2020-04-20 20:46:48 +02:00
2020-04-20 22:20:32 +02:00
Roll = Random.Range(0, TotalCumulativeChance);
AmbientEffect Effect = null;
for (int I = CumulativeChances.Length - 1; I >= 0; I--) {
if (Roll >= CumulativeChances[I]) {
if (Effects[I].RollsSinceLast <= RollsSince[I]) {
Effect = Effects[I];
RollsSince[I] = -1;
} else {
Effect = Effects[0];
}
2020-04-20 20:46:48 +02:00
break;
}
}
2020-04-20 22:20:32 +02:00
for (int I = 0; I < RollsSince.Length; I++) {
RollsSince[I]++;
}
float Distance = Random.Range(Effect.MinDistance, Effect.MaxDistance);
2020-04-20 20:46:48 +02:00
float Rads = Random.Range(0, 2 * Mathf.PI);
2020-04-20 22:20:32 +02:00
Vector3 Offset = new Vector3(Mathf.Cos(Rads) * Distance, Random.Range(Effect.MinY, Effect.MaxY), Mathf.Sin(Rads) * Distance);
2020-04-20 20:46:48 +02:00
GameObject Obj = Instantiate(AmbientSfxPrefab, transform.position + Offset, new Quaternion(), World);
AudioSource Sfx = Obj.GetComponent<AudioSource>();
2020-04-20 22:20:32 +02:00
if (Sfx != null && Effect.Clips.Length > 0) {
Sfx.clip = Effect.Clips[Random.Range(0, Effect.Clips.Length)];
2020-04-20 20:46:48 +02:00
Sfx.volume = Mathf.Sqrt(Random.Range(0.3f, 1f));
Sfx.Play();
}
}
}
}