- Home /
Object Sound Trigger
I've made an axe which is swinging from right to left and from left to right, but now I want to add a sound to it. I want that when the axe hits the middle of the swing, that it should play the sound, which is a "woosch" sound effect.
Here is my script:
public Rigidbody2D body2d;
public float leftPushRange;
public float rightPushRange;
public float velocityThreshold;
// Use this for initialization
void Start () {
body2d = GetComponent<Rigidbody2D>();
body2d.angularVelocity = velocityThreshold;
}
// Update is called once per frame
void Update () {
Push();
}
public void Push()
{
if (transform.rotation.z > 0
&& transform.rotation.z < rightPushRange
&& (body2d.angularVelocity > 0)
&& body2d.angularVelocity < velocityThreshold)
{
body2d.angularVelocity = velocityThreshold;
}
else if (transform.rotation.z < 0
&& transform.rotation.z > leftPushRange
&& (body2d.angularVelocity < 0)
&& body2d.angularVelocity > velocityThreshold * -1)
{
body2d.angularVelocity = velocityThreshold * -1;
}
}
How to do that?
deter$$anonymous$$e how many frames into the swing before you want the whoosh sound and use a coroutine?
public AudioClip whoosh;
public float whooshDelay;//time waiting for middle of swing;
//so in your script wherever it is you are starting the swing add:
StartCoroutine(DelayBeforeWhoosh());
private IEnumerator DelayBeforeWhoosh(){
yield return new WaitForSeconds(whooshDelay);
audio.PlayOneShot (whoosh);
}
}
I doesnt work and how do I know how many frames it has, when I did it with a hinge joint?
as for the frame #, just guess at first with a float of some value, say .5f. If it's too soon raise the value to .7f, if it's to late, lower the value . 3f. Adjust as needed til it's when you want it. As far as not working goes...nothing in that simple example to prevent it from working so the coroutine simply must not be initiating. add a Debug line in the coroutine to see if that's the problem. If you put the StartCoroutine in the spot that triggers the axe animation then it should work
Debug.Log ("coroutineWorking"); are there any error messages?
Answer by Besi2019 · Apr 15, 2018 at 10:07 AM
I thought I would add you to this question also, since you were so good at sound effect scripts.
Your answer
Follow this Question
Related Questions
Trigger sound on another gameobject 1 Answer
Sound on keypress, not working 2 Answers
How to get sound to play on barrel Explosion 1 Answer
Need help making an audio trigger. 2 Answers
How do I move an object from point A to point B using a trigger? 3 Answers