private void OnCollisionEnter2D(Collision2D collision) { if (this.playSoundsAtColision) { //MaterialWithSound mat = GetComponent<MaterialWithSound>(); if (sound != null) { if (collision.relativeVelocity.magnitude < minVelocityAtCollisionForCollisionSound) { return; } if (Mathf.Abs(collision.relativeVelocity.y) <= 0.01f) { return; } MaterialWithSound colMat = collision.gameObject.GetComponent <MaterialWithSound>(); if (colMat == null) { colMat = collision.gameObject.AddComponent <MaterialWithSound>(); //.SetDefaultValues(); Debug.LogWarning("'" + collision.gameObject.name + "' does not have a MaterialWithSound attatched. Attatching it dinamically", colMat.gameObject); } audioController.PlaySound(GetSoundOfColision(this, colMat, collision.relativeVelocity.magnitude), false, alertAlertablesOnCollision); //PlaySound(Sound.GetSoundOfColision(colMat, mat, collision.relativeVelocity.magnitude), false, true); } } }
public static Sound GetSoundOfColision(MaterialWithSound materialOfMovingObject, MaterialWithSound collidedMaterial, float relativeVelocity) { if (materialOfMovingObject.sound == null) { return(null); } //Construct the new sound Sound sound = (Sound)materialOfMovingObject.sound.Clone(); //Modify the sound to get the proper sound from the collision sound.pitch = 1 - materialOfMovingObject.objectSize; //As bigger the object, lower is the pitch float volumeByCollision = (relativeVelocity * sound.volume) / materialOfMovingObject.minVelocityAtCollisionForMaxSoundVolume; //The faster the collision, louder is the sound sound.volume = volumeByCollision * collidedMaterial.materialPhysics.hardness; //The harder the collided object, louder is the sound return(sound); }