在对象通过特定旋转时播放声音



每当物体旋转过某个点时,我都会尝试播放声音。代码工作正常,但后来它突然停止了,我不知道还能做什么。

该对象是一扇门,根据 Unity 的变换信息,它沿其 Z 轴从 -180 到 -300 旋转。我希望当门变换.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();
}
}

最新更新