using System; using System.Collections; using UnityEngine; namespace SpellBoundAR.MusicalInstruments.Piano { [DisallowMultipleComponent] [RequireComponent(typeof(AudioSource))] public abstract class PianoKey : MonoBehaviour { public static event Action OnPianoKeyPlayed; public event Action OnDownChanged; [SerializeField] protected Tone tone; [SerializeField] private bool overrideDefaultAudioClip; [SerializeField] private AudioClip audioClip; [Header("Animation Settings")] [SerializeField] protected float animationSecondsUp = .1f; [SerializeField] protected float animationSecondsDown = .05f; [Header("Cache")] private AudioSource _audioSource; private bool _down; public Tone Tone => tone; public bool Down { get => _down; private set { if (_down == value) return; _down = value; OnDownChanged?.Invoke(); } } private AudioSource AudioSource { get { if (!_audioSource) _audioSource = GetComponent(); return _audioSource; } } private AudioClip AudioClip => overrideDefaultAudioClip ? audioClip : tone ? tone.AudioClipPiano : null; public void PlayNote(PlayerType player) { AudioSource.clip = AudioClip; AudioSource.volume = 1f; AudioSource.Play(); OnPianoKeyPlayed?.Invoke(player, tone); if (Down) return; Down = true; StopAllCoroutines(); GoDown(); } public void StopNote() { if (!Down) return; Down = false; StopAllCoroutines(); GoUp(); StartCoroutine(ChangeVolumeOverSeconds(.5f)); } private IEnumerator ChangeVolumeOverSeconds(float seconds) { float startVolume = AudioSource.volume; for (float timer = 0f; timer < seconds; timer += Time.unscaledDeltaTime) { float progress = timer / seconds; AudioSource.volume = Mathf.Lerp(startVolume, 0, progress); yield return null; } AudioSource.volume = 0f; } protected abstract void GoDown(); protected abstract void GoUp(); } }