I have a simple script that makes a locker make 2 different sounds depending on what it collides with. If it collides with concrete it makes one sound and if it collides with another locker it makes a different sound.
Here it is:
var FloorSound : AudioClip;
var LockerSound : AudioClip;
function OnCollisionEnter (other : Collision) {
if (other.gameObject.tag == "Concrete") {
audio.clip = FloorSound;
audio.Play();
}
else if (other.gameObject.tag == "Locker") {
audio.clip = LockerSound;
audio.Play();
}
}
The problem I am getting is that at the start of the game the locker collides with the floor instantly and the sound goes off. Then because the locker never actually leaves the floor it doesn't make the sound again when I push it over. It collides with the other locker quite nicely so I know there isn't a problem as such with the code, it just needs something adding to it to keep it updating every time the locker collides with the floor.
You could probably fix this by examining the relativeVelocity reported by the collision in the OnCollisionStay method, and playing a sound if it exceeds some threshold. You could even change the volume of the sound based on the relativeVelocity.
Something like this:
(for illustrative purposes! - untested, may contain errors!)
var FloorSound : AudioClip;
var LockerSound : AudioClip;
var impactSoundThreshold = 0.5; // tweak this value
// both the "Enter" and the "Stay" collisions pass
// their data to the sound function:
function OnCollisionStay (collision : Collision) {
PlayCollisionSound(collision);
}
function OnCollisionEnter (collision : Collision) {
PlayCollisionSound(collision);
}
function PlayCollisionSound (collision : Collision) {
// check if the collision was hard enough to generate a sound
if (collision.relativeVelocity > impactSoundThreshold) {
// select the correct sound effect based on the object's tag
switch (collision.gameObject.tag) {
case "Concrete": audio.clip = FloorSound; break;
case "Locker": audio.clip = LockerSound; break;
}
// calculate the volume (anything above 4*Threshold = full volume)
var volume = Mathf.InverseLerp(impactSoundThreshold, impactSoundThreshold*4, collision.relativeVelocity);
// play the audio
audio.volume = volume;
audio.Play();
}
}
I am not a coder but I had something similiar ... If your locker is always on the concrete then you shouldn't use the collision with the concrete to activate the sound. Try to link it when you character is pulling it iPushLocker = true;. you should also consider looping the sound while you push...
I decided to take out the difference in sound files as this was complicating things a little and made some funny sounds but you can add it back in quite easily.