campfire/Assets/Scripts/CampfireSfx.cs

71 lines
2.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CampfireSfx : MonoBehaviour {
public AudioSource ActiveBurnSource;
public AudioSource AmbientSource;
public AudioSource IntenseAmbientSource;
public Campfire Campfire;
public float ActiveBurn = 0f;
[Header("Clips")]
public AudioClip EndClip;
public AudioClip[] AmbientClips;
public AudioClip[] IntenseAmbientClips;
public AudioClip[] CrackleClips;
private void Update() {
ActiveBurn = Mathf.Max(0, ActiveBurn - Time.deltaTime);
ActiveBurnSource.pitch = Time.timeScale;
AmbientSource.pitch = Time.timeScale;
IntenseAmbientSource.pitch = Time.timeScale;
if (Campfire.TimeToEnd <= 0) {
IntenseAmbientSource.volume = Mathf.Lerp(IntenseAmbientSource.volume, 0, 10f * Time.deltaTime);
ActiveBurnSource.volume = Mathf.Lerp(ActiveBurnSource.volume, 0, 10f * Time.deltaTime);
AmbientSource.volume = Mathf.Lerp(AmbientSource.volume, 0, 10f * Time.deltaTime);
return;
} else {
IntenseAmbientSource.volume = Mathf.Max(ActiveBurn, Mathf.Clamp((Campfire.Fuel - Campfire.GoodFuelAmount) / Campfire.GoodFuelAmount, 0, 1));
ActiveBurnSource.volume = Mathf.Pow(ActiveBurn, 0.3f);
AmbientSource.volume = Mathf.Lerp(AmbientSource.volume, 1, 10f * Time.deltaTime);
}
bool StartEndClip = Campfire.TimeToEnd <= EndClip.length && AmbientSource.clip != EndClip;
bool StopEndClip = Campfire.TimeToEnd > EndClip.length && AmbientSource.clip == EndClip;
if (StartEndClip) {
AmbientSource.clip = EndClip;
AmbientSource.Play();
AmbientSource.time = EndClip.length - Campfire.TimeToEnd;
} else if (StopEndClip || NeedsRefresh(AmbientSource)) {
AmbientSource.clip = RandomClip(AmbientClips);
AmbientSource.Play();
}
if (NeedsRefresh(IntenseAmbientSource)) {
IntenseAmbientSource.clip = RandomClip(IntenseAmbientClips);
IntenseAmbientSource.Play();
}
if (ActiveBurn > 0 && NeedsRefresh(ActiveBurnSource)) {
ActiveBurnSource.clip = RandomClip(CrackleClips);
ActiveBurnSource.Play();
}
}
private bool NeedsRefresh(AudioSource source) {
return !source.isPlaying || source.clip == null || (source.clip.length - source.time) <= Time.deltaTime;
}
private AudioClip RandomClip(AudioClip[] clips) {
if (clips.Length > 0) {
return clips[Random.Range(0, clips.Length)];
} else {
return null;
}
}
}