Âm thanh bước chân theo bề mặt
C# Code
using UnityEngine;
using System.Collections.Generic;
public class FootstepSound : MonoBehaviour
{
public AudioSource audioSource;
public float stepRate = 0.5f;
public float stepCooldown = 0.5f;
private float lastStepTime = 0f;
// Định nghĩa âm thanh cho từng loại bề mặt
[System.Serializable]
public class SurfaceSound
{
public string tag;
public AudioClip[] clips;
}
public List<SurfaceSound> surfaceSounds = new List<SurfaceSound>();
private Dictionary<string, AudioClip[]> soundDictionary = new Dictionary<string, AudioClip[]> ();
void Start()
{
// Chuyển List thành Dictionary để truy cập nhanh hơn
foreach (var ss in surfaceSounds)
{
soundDictionary[ss.tag] = ss.clips;
}
}
// Gọi hàm này từ Animation Event trong animation đi/chạy của nhân vật
public void PlayFootstepSound()
{
// Kiểm tra cooldown để tránh phát âm thanh quá dày
if (Time.time - lastStepTime < stepCooldown) return;
lastStepTime = Time.time;
// Bắn một Raycast xuống dưới để xác định bề mặt
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.5f))
{
string surfaceTag = hit.collider.tag;
if (soundDictionary.ContainsKey(surfaceTag))
{
AudioClip[] clips = soundDictionary[surfaceTag];
if (clips.Length > 0)
{
AudioClip clip = clips[Random.Range(0, clips.Length)];
audioSource.PlayOneShot(clip);
}
}
else
{
// Phát âm thanh mặc định nếu không tìm thấy tag
// (Bạn có thể thêm một SurfaceSound với tag "Untagged")
}
}
}
}Phát ra các âm thanh bước chân khác nhau tùy thuộc vào loại bề mặt vật liệu (qua Tag) mà người chơi đang đi trên đó, ví dụ: cỏ, gỗ, đá.