Last active
August 30, 2018 03:45
-
-
Save beardordie/507e4f0e2c2ab2294bc534566f352951 to your computer and use it in GitHub Desktop.
Play audio clip based on a rigidbody's collision force, with pitch variance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
[RequireComponent(typeof(AudioSource))] | |
[RequireComponent(typeof(Collider))] | |
public class CollisionAudio : MonoBehaviour | |
{ | |
[SerializeField] private AudioClip collideSoft; | |
[SerializeField] private AudioClip collideHard; | |
[SerializeField] private float lowPitchRange = .75F; | |
[SerializeField] private float highPitchRange = 1.5F; | |
[SerializeField] private float velocityClipSplit = 10F; // under this volume, use soft sound | |
// over this volume, use hard sound | |
private float velToVol = .2F; | |
private AudioSource audioSource; | |
void Awake() | |
{ | |
audioSource = GetComponent<AudioSource>(); | |
} | |
private void Reset() | |
{ | |
if (!audioSource) audioSource = GetComponent<AudioSource>(); | |
} | |
void OnCollisionEnter(Collision coll) | |
{ | |
audioSource.pitch = Random.Range(lowPitchRange, highPitchRange); | |
float hitVol = coll.relativeVelocity.magnitude * velToVol; | |
if (coll.relativeVelocity.magnitude < velocityClipSplit) | |
audioSource.PlayOneShot(collideSoft, hitVol); | |
else | |
audioSource.PlayOneShot(collideHard, hitVol); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment