2020-05-02 23:47:34 +02:00
using System.Collections ;
using System.Collections.Generic ;
using UnityEngine ;
[RequireComponent(typeof(Rigidbody))]
public class CollisionSfx : MonoBehaviour {
public LayerMask Mask ;
public AudioClip [ ] Clips ;
public AudioSource Source ;
public float EffectCooldown ;
[Tooltip("When the game starts, a lot of sticks drop (because they spawn). This is the amount of time that the stick should stay silent after spawning.")]
public float WaitUntilSfxAtGameStart ;
private Rigidbody Body ;
private float LastTimePlayed = 0 ;
2020-05-03 23:09:44 +02:00
private static float LastTimeGloballyPlayed = 0 ;
private static readonly float GlobalCooldown = 0.05f ;
2020-05-02 23:47:34 +02:00
private void Awake ( ) {
Body = GetComponent < Rigidbody > ( ) ;
}
private void Start ( ) {
LastTimePlayed = Time . time + WaitUntilSfxAtGameStart ;
}
private bool PlaySound ( ) {
2020-05-03 23:09:44 +02:00
if ( Time . time - LastTimePlayed > = EffectCooldown & & Time . time - LastTimeGloballyPlayed > = GlobalCooldown ) {
2020-05-02 23:47:34 +02:00
LastTimePlayed = Time . time ;
2020-05-03 23:09:44 +02:00
LastTimeGloballyPlayed = Time . time ;
2020-05-02 23:47:34 +02:00
if ( Clips . Length > 0 ) {
Source . PlayOneShot ( Clips [ Random . Range ( 0 , Clips . Length ) ] , Mathf . Sqrt ( Body . velocity . magnitude ) ) ;
return true ;
}
}
return false ;
}
private void OnCollisionEnter ( Collision collision ) {
if ( ( ( 1 < < collision . gameObject . layer ) & Mask . value ) ! = 0 ) {
PlaySound ( ) ;
}
}
}