﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class ParticleCollisionSound : MonoBehaviour
{
    //reusable shared buffer for particle collisions because there can be a LOT of them very easily.
    static List<ParticleCollisionEvent> collisionEventBuffer = new List<ParticleCollisionEvent>();

    //the clip to play when a particle collides
    public AudioClip clip;
    [Range(0,1)]
    public float minVolume = 0.25f;
    [Range(0, 1)]
    public float maxVolume = 1;
    public float minVelocity = 2;
    public float maxVelocity = 10;

    AudioSource source;

    private void Start()
    {
        //cache audio source reference for playing particle collision sounds
        source = GetComponent<AudioSource>();
    }

    //When a particle hits the collider, it sends a message.
    private void OnParticleCollision(GameObject sender)
    {
        //sender definitely has a ParticleSystem on it because it sent this message
        var pSys = sender.GetComponent<ParticleSystem>();
        //get the collisions from this frame that occurred on this collider only, put them in a buffer.
        int count = pSys.GetCollisionEvents(gameObject, collisionEventBuffer);
        //loop over however many collision events were returned
        for (int i = 0; i < count; i++)
        {
            //get a reference to the specific collision (this is very important as it is a struct)
            ParticleCollisionEvent collision = collisionEventBuffer[i];

            //normalize the velocity to do something interesting with it
            float p = Mathf.InverseLerp(minVelocity, maxVelocity, collision.velocity.magnitude);
            //disregard stuff that's too slow
            if (p == 0)
                continue;

            //play velocity attenutated clip!
            source.PlayOneShot(clip, Mathf.Lerp(minVolume, maxVolume, p));
        }
    }
}
