- Home /
How do I change footstep sounds on different surfaces?
So I have these two scripts, one is a First-Person Controller script, and the other is a script that changes footstep audio when a FPC character is on different textures. However, I can't get the two to work together. By taking a look at the scripts, does anyone know how I can get the two scripts to work with each other?
Scripts:
(FPC Script)
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
(Footstep System Script)
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class SmartFootstepSystem : MonoBehaviour {
[System.Serializable]
public class GroundType{
public string name;
public Texture2D[] textures;
public AudioClip[] sounds;
}
public AudioSource footstepAudio;
public float groundCheckDistance = 0.25f;
public List <GroundType> groundTypes = new List<GroundType>();
private Terrain terrain;
private TerrainData terrainData;
private SplatPrototype[] splatPrototypes;
private RaycastHit hit;
[HideInInspector]public Texture2D currentTexture;
[HideInInspector]public bool onTerrain;
void Start(){
GetTerrainInfo();
}
void GetTerrainInfo(){
if(Terrain.activeTerrain){
terrain = Terrain.activeTerrain;
terrainData = terrain.terrainData;
pragma warning disable CS0618 // Type or member is obsolete
splatPrototypes = terrain.terrainData.splatPrototypes;
pragma warning restore CS0618 // Type or member is obsolete
}
}
void Update () {
Ray ray = new Ray(transform.position + (Vector3.up * 0.1f), Vector3.down);
//check if the character is currently on a terrain or renderer and get the tecture at that position
if(Physics.Raycast(ray, out hit, groundCheckDistance)){
if(hit.collider.GetComponent<Terrain>()){
currentTexture = splatPrototypes[GetMainTexture(transform.position)].texture;
onTerrain = true;
}
if(hit.collider.GetComponent<Renderer>()){
currentTexture = GetRendererTexture();
onTerrain = false;
}
}
//helper to visualize the ground checker ray
#if UNITY_EDITOR
Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * groundCheckDistance),Color.green);
#endif
}
public void Footstep(){
for(int i = 0; i < groundTypes.Count; i++){
for(int k = 0; k < groundTypes[i].textures.Length; k++){
if(currentTexture == groundTypes[i].textures[k]){
footstepAudio.PlayOneShot(groundTypes[i].sounds[Random.Range(0,groundTypes[i].sounds.Length)]);
}
}
}
}
/*returns an array containing the relative mix of textures
on the main terrain at this world position.*/
public float[] GetTextureMix(Vector3 worldPos) {
terrain = Terrain.activeTerrain;
terrainData = terrain.terrainData;
Vector3 terrainPos = terrain.transform.position;
int mapX = (int)(((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
int mapZ = (int)(((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
float[,,] splatmapData = terrainData.GetAlphamaps(mapX,mapZ,1,1);
float[] cellMix = new float[splatmapData.GetUpperBound(2)+1];
for (int n=0; n<cellMix.Length; ++n){
cellMix[n] = splatmapData[0,0,n];
}
return cellMix;
}
/*returns the zero-based index of the most dominant texture
on the main terrain at this world position.*/
public int GetMainTexture(Vector3 worldPos) {
float[] mix = GetTextureMix(worldPos);
float maxMix = 0;
int maxIndex = 0;
for (int n=0; n<mix.Length; ++n){
if (mix[n] > maxMix){
maxIndex = n;
maxMix = mix[n];
}
}
return maxIndex;
}
//returns the mainTexture of a renderer's material at this position
public Texture2D GetRendererTexture(){
Texture2D texture = null;
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hit, groundCheckDistance)){
if(hit.collider.gameObject.GetComponent<Renderer>()){
MeshFilter meshFilter = (MeshFilter)hit.collider.GetComponent(typeof(MeshFilter));
Mesh mesh = meshFilter.mesh;
int totalSubMeshes = mesh.subMeshCount;
int[] subMeshes = new int[totalSubMeshes];
for(int i = 0; i < totalSubMeshes; i++){
subMeshes[i] = mesh.GetTriangles(i).Length / 3;
}
int hitSubMesh = 0;
int maxVal = 0;
for(int i = 0; i < totalSubMeshes; i ++){
maxVal += subMeshes[i];
if(hit.triangleIndex <= maxVal - 1){
hitSubMesh = i + 1;
break;
}
}
texture = (Texture2D)hit.collider.gameObject.GetComponent<Renderer>().materials[hitSubMesh - 1].mainTexture;
}
}
return texture;
}
}
Your answer
Follow this Question
Related Questions
Sprinting Problem 0 Answers
How can i make my audio loop faster/slower? 0 Answers
footstep audio sync probs 0 Answers
My Footstep isn't working 2 Answers