How to get particle velocity to affect audio amplitude
Hi, I'm new to Unity. I have particle collisions triggering audio but I'm unsure on how to get their velocity to control the audio amplitude.
The audio is coming from a puredata patch using Kalimba but an answer related to a general audio source would still be very useful.
Thanks in advance.
Answer by ifurkend · Jul 13, 2020 at 12:47 AM
You can refer to OnParticleCollision and ParticleCollisionEvent. Since the "velocity" you get from collision event is a vector3, you need to calculate its magnitude before apply it for the audio amplitude/volume. The following code also remaps and clamps the speed value to better control the resultant volume. To understand the speed range of your particle system, look at the "Particle Effect" console at the bottom-right corner of the Scene view, this can help you better estimate the proper speed range.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ParticleCollisionMessage : MonoBehaviour
{
public ParticleSystem _particleSystem;
public AudioSource _audioSource;
public Vector2 _speedRange = new Vector2(0f,1f);
public Vector2 _volumeRange = new Vector2(0f,1f);
public List<ParticleCollisionEvent> collisionEvents;
void Start()
{
if (_particleSystem == null) _particleSystem = this.GetComponent<ParticleSystem>();
collisionEvents = new List<ParticleCollisionEvent>();
}
void OnParticleCollision(GameObject other)
{
int numCollisionEvents = _particleSystem.GetCollisionEvents(other, collisionEvents);
int i = 0;
while (i < numCollisionEvents)
{
float _speed = collisionEvents[i].velocity.magnitude;
float _volume = Remap(_speed, _speedRange.x, _speedRange.y, _volumeRange.x, _volumeRange.y);
_volume = Mathf.Clamp(_volume, _volumeRange.x, _volumeRange.y);
_audioSource.volume = _volume;
_audioSource.Play();
i++;
//Debug.Log(_volume);
}
}
float Remap (float _value, float _low1, float _high1, float _low2, float _high2) {
return _low2 + (_value - _low1) * (_high2 - _low2) / (_high1 - _low1);
}
}
Thanks @ifurkend , that all makes sense and I've implemented the code in my project. I'm just having trouble with adapting line #29.
I have an amplitude slider in my puredata patch ranging from 0-127. I'm using Kalimba to link Unity to the puredata patch and I'm not sure how to reference the slider ins$$anonymous$$d of the Audio Source volume parameter.
I'm not sure if this helps for Kalimba context/syntax, but there's a pull request relating to the volume slider here
Thanks again and I'd be grateful for any futher assistance.