campfire/Assets/Scripts/CollisionSfx.cs

46 lines
1.4 KiB
C#

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;
private static float LastTimeGloballyPlayed = 0;
private static readonly float GlobalCooldown = 0.05f;
private void Awake() {
Body = GetComponent<Rigidbody>();
}
private void Start() {
LastTimePlayed = Time.time + WaitUntilSfxAtGameStart;
}
private bool PlaySound() {
if (Time.time - LastTimePlayed >= EffectCooldown && Time.time - LastTimeGloballyPlayed >= GlobalCooldown) {
LastTimePlayed = Time.time;
LastTimeGloballyPlayed = Time.time;
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();
}
}
}