Skip to content

Instantly share code, notes, and snippets.

@CosmoCleaner
Last active February 8, 2017 06:47
Show Gist options
  • Save CosmoCleaner/6d2e088f7973d39896fd to your computer and use it in GitHub Desktop.
Save CosmoCleaner/6d2e088f7973d39896fd to your computer and use it in GitHub Desktop.
Unityで足音を鳴らすためのスクリプト
using UnityEngine;
using System;
using System.Collections;
/// <summary>
/// 足の接地を感知して音を鳴らす
/// </summary>
public class FootStepDetector : MonoBehaviour {
public FootStepSounds footStepSounds;
private AudioSource aSource;
// 足音の最短間隔
private const float PLAY_INTERVAL_MIN_SEC = 0.4f;
// 最後に足音鳴らした時刻
private DateTime lastStepTime;
#region unity
void Start ()
{
aSource = gameObject.GetComponent<AudioSource> ();
lastStepTime = DateTime.Now;
}
#endregion
void OnTriggerEnter (Collider col)
{
if ((DateTime.Now - lastStepTime).TotalSeconds < PLAY_INTERVAL_MIN_SEC) {
// タップダンス的な足音連打事故を防ぐ
return;
}
FootStepSounds.StepInfo info = footStepSounds.stepInfos.Find ((i) => i.groundTag == col.gameObject.tag);
if (info.HasValue()) {
aSource.clip = info.GetClipRandomely ();
aSource.Play ();
lastStepTime = DateTime.Now;
}
}
}
using UnityEngine;
using System;
using System.Collections.Generic;
/// <summary>
/// 足音音源を管理
/// </summary>
public class FootStepSounds : MonoBehaviour
{
/// <summary>
/// 地面と音の対応情報
/// </summary>
[Serializable]
public struct StepInfo
{
// 地面タグ
public string groundTag;
// 地面に対応した音
public List<AudioClip> clips;
public bool HasValue(){
return !string.IsNullOrEmpty (groundTag) && clips != null && clips.Count > 0;
}
public AudioClip GetClipRandomely(){
return clips [UnityEngine.Random.Range (0, clips.Count)];
}
}
public List<StepInfo> stepInfos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment