using UnityEngine;
using System.Collections;
public class AdvancedFootsteps : MonoBehaviour
{
// character controller reference
CharacterController characterController;
// script referencec
tpAnimator tpanimator;
// audio source
AudioSource audio;
//Audio clips
public AudioClip woodStep;
public AudioClip waterStep;
public AudioClip metalStep;
public AudioClip grassStep;
public AudioClip dirtStep;
public AudioClip stoneStep;
public AudioClip sandStep;
// intervals between steps
float runningInterval = 0.2f;
float walkingInterval = 0.5f;
float crouchingInterval = 1f;
/** step volumes
float runningVolume;
float walkingVolume;
float crouchingVolume; **/
bool playsteps;
void Awake ()
{
characterController = GetComponent<tpController> ().characterController;
tpanimator = GetComponent<tpAnimator> ();
audio = GetComponent<AudioSource> ();
}
void Start ()
{
playsteps = true;
StartCoroutine ("PlayFootsteps");
}
void Update ()
{
Debug.Log ("Update");
if (characterController.isGrounded && !playsteps && characterController.velocity.magnitude > 0.2f) {
playsteps = true;
StartCoroutine ("PlayFootsteps");
}
if (!characterController.isGrounded && playsteps) {
playsteps = false;
StopCoroutine ("PlayFootsteps");
}
}
IEnumerator PlayFootsteps ()
{
float vel = characterController.velocity.magnitude;
RaycastHit hit;
string floorTag;
if (characterController.isGrounded && vel > 0.2f) {
if (Physics.Raycast (transform.position, Vector3.down, out hit)) {
floorTag = hit.collider.gameObject.tag;
if (floorTag == "Wood") {
audio.clip = woodStep;
} else if (floorTag == "Water") {
audio.clip = waterStep;
} else if (floorTag == "Metal") {
audio.clip = metalStep;
} else if (floorTag == "Terrain") {
// check texture and get correct clip
int t = GetMainTexture (transform.position);
switch (t) {
case 0:
// grass
audio.clip = grassStep;
break;
case 1:
// dirt
audio.clip = dirtStep;
break;
case 2:
// stone
audio.clip = stoneStep;
break;
case 3:
// gravel
audio.clip = stoneStep;
break;
case 4:
// sand
audio.clip = dirtStep;
break;
case 5:
// wet mud
audio.clip = dirtStep;
break;
case 6:
// branches
audio.clip = stoneStep;
break;
case 7:
// snow
audio.clip = stoneStep;
break;
case 8:
// concrete
audio.clip = dirtStep;
break;
}
}
// Play the correct sound
audio.PlayOneShot (audio.clip);
if (tpanimator.isRunning) {
yield return new WaitForSeconds (runningInterval);
} else if (tpanimator.isCrouching) {
yield return new WaitForSeconds (crouchingInterval);
} else {
yield return new WaitForSeconds (walkingInterval);
}
playsteps = false;
} else {
yield return null;
}
}
}
}
Edit: working script, i will not take credit for most of the code since it is a combination of scripts found on this site.