campfire/Assets/Scripts/CampfireSfx.cs

72 lines
2.7 KiB
C#
Raw Normal View History

2020-04-19 18:42:40 +02:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CampfireSfx : MonoBehaviour {
2020-04-19 22:09:31 +02:00
public GameState GameState;
2020-04-19 18:42:40 +02:00
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);
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 {
2020-04-20 04:18:33 +02:00
IntenseAmbientSource.volume = Mathf.Max(ActiveBurn, Mathf.Clamp((Campfire.Fuel - Campfire.GoodFuelAmount) / Campfire.GoodFuelAmount, 0, 1) * 0.2f);
2020-04-19 18:42:40 +02:00
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;
2020-04-19 22:09:31 +02:00
bool StopEndClip = AmbientSource.clip == EndClip && (Campfire.TimeToEnd > EndClip.length || GameState.Current == State.Paused);
2020-04-19 18:42:40 +02:00
if (StartEndClip) {
AmbientSource.clip = EndClip;
2020-04-19 20:04:45 +02:00
AmbientSource.time = Mathf.Clamp(EndClip.length - Campfire.TimeToEnd, 0, EndClip.length - 0.01f);
2020-04-19 18:42:40 +02:00
AmbientSource.Play();
} else if (StopEndClip || NeedsRefresh(AmbientSource)) {
2020-04-19 20:04:45 +02:00
Refresh(AmbientSource, AmbientClips);
2020-04-19 18:42:40 +02:00
}
if (NeedsRefresh(IntenseAmbientSource)) {
2020-04-19 20:04:45 +02:00
Refresh(IntenseAmbientSource, IntenseAmbientClips);
2020-04-19 18:42:40 +02:00
}
if (ActiveBurn > 0 && NeedsRefresh(ActiveBurnSource)) {
2020-04-19 20:04:45 +02:00
Refresh(ActiveBurnSource, CrackleClips);
}
}
private void Refresh(AudioSource source, AudioClip[] clips) {
source.clip = RandomClip(clips);
if (source.clip != null) {
source.time = 0f;
source.Play();
2020-04-19 18:42:40 +02:00
}
}
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;
}
}
}