c# - 当对象经过特定旋转时播放声音
问题描述
每当对象旋转通过某个点时,我都会尝试播放声音。代码工作正常,但突然停止了,我不知道还能做什么。
该对象是一扇门,根据 Unity 的变换信息,它沿其 Z 轴从 -180 旋转到 -300。我希望在门 transform.rotation.z 小于 -190 时播放声音“portaFechando”,但它不起作用。
我只能听到“portaAbrindo”的声音。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class abrirPorta : MonoBehaviour
{
Animator anim;
bool portaFechada = true;
public AudioSource audio;
public AudioClip abrindo;
public AudioClip fechando;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
// checkando input para abrir a porta
if (Input.GetKeyDown("space") && portaFechada == true)
{
anim.SetBool("portaFechada", false);
anim.SetFloat("portaSpeed", 1);
portaFechada = false;
audio.clip = abrindo;
audio.Play();
}
// checkando input para fechar porta
else if (Input.GetKeyDown("space") && portaFechada == false)
{
anim.SetBool("portaFechada", true);
anim.SetFloat("portaSpeed", -1);
portaFechada = true;
}
// tocando som de fechando checkando rotação (bugou)
if (portafechada == false && transform.rotation.z <= -190)
{
Debug.Log("Worked!");
audio.clip = fechando;
audio.Play();
}
}
}
解决方案
目前,您正在访问四元数的 z 分量,它不是围绕 z 轴的角度的度量。
相反,请参考transform.eulerAngles.z
,它将是 0 到 360 之间的值。这里,-190 相当于 170,-300 相当于 60,因此,您可以检查是否transform.eulerAngles.z
小于或等于 170。
我还建议跟踪自按下关门按钮后是否已经播放了关闭声音。portafechada
此外,您不想只在为假时播放声音,而是只想在它为真时播放它:
Animator anim;
bool portaFechada = true;
public AudioSource audio;
public AudioClip abrindo;
public AudioClip fechando;
private bool playedSoundAlready = true;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
// checkando input para abrir a porta
if (Input.GetKeyDown("space") && portaFechada)
{
anim.SetBool("portaFechada", false);
anim.SetFloat("portaSpeed", 1);
portaFechada = false;
audio.clip = abrindo;
audio.Play();
}
// checkando input para fechar porta
else if (Input.GetKeyDown("space") && !portaFechada)
{
anim.SetBool("portaFechada", true);
anim.SetFloat("portaSpeed", -1);
portaFechada = true;
playedSoundAlready = false;
}
// tocando som de fechando checkando rotação (bugou)
if (!playedSoundAlready && portaFechada && transform.eulerAngles.z <= 170)
{
playedSoundAlready = true;
Debug.Log("Worked!");
audio.clip = fechando;
audio.Play();
}
}
推荐阅读
- hybris - 创建新组件或小部件以在产品页面模板中的 Grid 和 List 视图之间切换
- android - 如何给一个应用程序,在我自己的 AOSP -eng 版本上运行,root 权限?
- python - 如何将元组列表转换为具有重复键的字典?
- python - 使用 sklearn 模块提取 3 个最佳匹配项
- typescript - 根据承诺的结果在量角器中创建动态它
- ios - async function run() { ^^^^^^^^ SyntaxError: Unexpected token function
- sql-server - 为什么在 SQL Server 中违反 PRIMARY KEY 约束返回错误代码 2627 而不是 2601?
- django - Django:如何让 setUpTestData 为所有测试运行一次?
- angular - 如何更改 *ngFor 中的单个 mouseover 和 mouseout 事件?
- powershell - 如何使用 PowerShell 将字符替换为 $_