Unity3D – Walking Footsteps – SFX – JavaScript
Create a scene with:
– Main Camera -> Audio Listener component
– Cube -> Audio Source component
-> WalkSfx.js
#pragma strict // Audio var START ------------------------------- var footsteps : AudioClip[]; // Assign in Inspector private var step : boolean = true; var audioStepLengthWalk = 0.58f; // Audio var END --------------------------------- function Start () { }// END Start function Update () { Debug.Log(step);// show step status // move START -------------------------------- var horiz : float = Input.GetAxis("Horizontal"); transform.Translate(Vector3(horiz,0,0)); // move END ---------------------------------- // AudioPlay START --------------------------- if (Input.GetAxis("Horizontal") && step) { Walk(); } // AudioPlay END ----------------------------- }// END Update() // ############################################### // Audio functions START ######################### function Walk(){ audio.clip = footsteps[Random.Range(0, footsteps.Length)]; audio.volume = 1.0f; audio.Play(); WaitForFootStepsCoroutine(audioStepLengthWalk);// wait time -> audioStepLengthWalk }// END Walk() function WaitForFootStepsCoroutine (stepsLength : float){ step = false; yield WaitForSeconds(stepsLength); step = true; }// WaitForFootStepsCoroutine() // Audio functions END ############################ // ################################################
Inspector> Assign 4 different Audio Clip to var footsteps
Play
For italian people: come funziona?
1. if (Input.GetAxis(“Horizontal”) && step) -> se premo i tasti dello spostamento e la variabile step è TRUE
2. viene avviata la funzione Walk();
3. Walk():
– seleziona dall’array una clip random, ce ne servono almeno 4 o il suono risulterà noioso
– setta il volume -> audio.volume = 1.0f;
– avvia l’audio -> audio.Play();
– avvia WaitForFootStepsCoroutine(), inviando audioStepLengthWalk
4. WaitForFootStepsCoroutine():
– audioStepLengthWalk = stepsLength
– step = FALSE per evitare che -> if (Input.GetAxis(“Horizontal”) provochi la riproduzione della clip sonora ad ogni frame
– yield WaitForSeconds(stepsLength); -> mantiene step = FALSE per i secondi di stepsLength -> poi step = TRUE
5. con step = TRUE -> riparte if (Input.GetAxis(“Horizontal”) && step) per avviare una nuova clip audio