campfire/Assets/Scripts/CollisionSfx.cs

42 lines
1.2 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 void Awake() {
Body = GetComponent<Rigidbody>();
}
private void Start() {
LastTimePlayed = Time.time + WaitUntilSfxAtGameStart;
}
private bool PlaySound() {
if (Time.time - LastTimePlayed >= EffectCooldown) {
LastTimePlayed = 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();
}
}
}