Search Unity

trying to play sound when ball is grounded

Discussion in 'Scripting' started by Azaroth99, Feb 13, 2016.

  1. Azaroth99

    Azaroth99

    Joined:
    Jul 1, 2014
    Posts:
    1
    Hello friends, I am making a game where the player is a ball that rolls around. I have a problem making a script that makes a sound when the ball is rolling. Here is my script.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(AudioSource))]
    5. public class PlayRoll : MonoBehaviour {
    6.     private bool grounded;
    7.  
    8.  
    9.     void Start() {
    10.    
    11.         grounded = false;
    12.  
    13.     }
    14.  
    15.     void OnTriggerEnter(Collider other)
    16.     {
    17.  
    18.         if (other.gameObject.CompareTag ("ground"))
    19.         {
    20.  
    21.             grounded = true;
    22.  
    23.         }
    24.             else
    25.         {
    26.                 grounded = false;
    27.             }
    28.  
    29.         playSoundWhenGrounded ();
    30.      
    31. }
    32.     void playSoundWhenGrounded() {
    33.        
    34.         AudioSource audio = GetComponent<AudioSource>();
    35.        
    36.         if (grounded == true) {
    37.             audio.Play();
    38.            
    39.         }
    40.        
    41.     }
    42. }
    43.  
    44.  
    also, if u know a way to make that sound only when the ball is gaining speed, so that it wont play this sound when is grounded but the ball is not moving, don't hesitate to tell me :). Thank you!
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You need an onCollisionLeave too, and set the grounded to false there.
    The speeding up bit:
    Code (CSharp):
    1. Pseudo(kinda) code:
    2. Vector3 pos: pos at startup
    3. float vBefore: 0
    4.  
    5. Update:
    6.    float v: current pos - pos
    7.    if v > vBefore
    8.       play sound
    9.    endIf
    10.    vBefore = v
    11.    pos = current pos
    12. EndOfUpdate
    13.