C# 以与速度相关的间隔播放滴答声的最有效方法?
我有一个有锋利边缘的球,我想模拟球滚动时的咔哒声。我将如何以与球的速度相关的间隔播放滴答声?随着球的速度增加,滴答声变得更加频繁 当前可用变量:C# 以与速度相关的间隔播放滴答声的最有效方法?,c#,audio,unity3d,unity5,C#,Audio,Unity3d,Unity5,我有一个有锋利边缘的球,我想模拟球滚动时的咔哒声。我将如何以与球的速度相关的间隔播放滴答声?随着球的速度增加,滴答声变得更加频繁 当前可用变量: AudioClip[] tickSounds; // the sound files bool onGround; // indicates if the ball is on the ground Rigidbody rb; // Rigidbody of the ball to access vel
AudioClip[] tickSounds; // the sound files
bool onGround; // indicates if the ball is on the ground
Rigidbody rb; // Rigidbody of the ball to access velocity
我试过时间、帧数和调制,但没能获得好的节奏
提前谢谢。想好了!使用协同程序
void Start() {
StartCoroutines("TickSound", 30f); // method name, initial wait time
}
IEnumerator TickSound(float time) {
yield return new WaitForSeconds(time);
while (true) {
// Don't bother playing sounds if its below a certain velocity
if (onGround && rb.velocity.magnitude > 1f) {
au.PlayOneShot(tickSounds[Random.Range(0, tickSounds.Length)], 0.2f);
}
// Used this equation 0.6f / ((velocity / 3f) + 1)
yield return new WaitForSeconds(0.6f / (rb.velocity.magnitude / 3f + 1)) ;
}
}
即使你的答案有效,我也建议使用
浮点计时器代码>变量以存储时间并使用计时器+=time.deltaTime代码>在更新()
中。如果您的计时器
值为>0.6f/(rb.velocity.magnity/3f+1)
,则将其重置为0并播放声音。这样可以避免无限次的协同进程运行。