Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Sound when ball hits and not when rolling?

Discussion in 'Scripting' started by macmouse, Oct 19, 2014.

  1. macmouse

    macmouse

    Joined:
    Jun 5, 2014
    Posts:
    37
    Hello,

    I have a 2d soccer ball. You can kick it.
    Now, I want to play a sound, when the ball falls down and hits the ground. One or more times. But I don't want to play a sound, when the ball is rolling.

    How can I do that? I searched a little bit. Is this the answer?:
    rigidbody.velocity.magnitude > 0.5

    And is there a way to make the sound higher or lower depending on the hit? For what I must search for?
     
    Last edited: Oct 19, 2014
  2. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    Use this built-in function to run code when the ball collides with something.
    You can use the relative velocity to play a sound when needed. ;o
     
  3. macmouse

    macmouse

    Joined:
    Jun 5, 2014
    Posts:
    37
    Hmm, but what is when the ball touching the ground and rolling. Collider.OnCollisionEnter does not stop. It's always collision enter?
     
  4. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    What do you mean, it gets called when you physically iteract with another object.
     
  5. DylanYasen

    DylanYasen

    Joined:
    Oct 9, 2013
    Posts:
    50
    can't really know what exactly u are doing and how you did it.
    but I assume that what you want to do is only play hit sound when ball hit the ground, not when on the ground.

    So you can set up this way. just need a simple boolean toggle to control:

    Code (CSharp):
    1. public AudioClip hitclip;
    2. bool hitGround;
    3.  
    4.  
    5. void PlayHitSound(){
    6. AudioSource.PlayAtPoint(hitclip,transform.position);
    7. }
    8.  
    9. void OnCollisionEnter2D(Collision2d other){
    10.  
    11. // you may want to add a condition here
    12. // if other.tag == "ground";
    13.  
    14. if(!hitGround){
    15. PlayHitSound();
    16.  
    17. hitGround = true;
    18. }
    19. }
    20.  
    21. void OnCollisionExit2D(Collision2d other){
    22. hitGround = false;
    23. }
    24.  
    25.  
    26.  
    27.