campfire/Assets/Scripts/AmbientSoundGenerator.cs

67 lines
2.4 KiB
C#
Raw Normal View History

2020-04-20 20:46:48 +02:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
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
private void Awake() {
World = GameObject.FindGameObjectWithTag("World").transform;
2020-04-20 22:20:32 +02:00
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 20:46:48 +02:00
}
private void Update() {
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();
}
}
}
}