首页 > 解决方案 > 当对象经过特定旋转时播放声音

问题描述

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

该对象是一扇门,根据 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();

        }



    }
}

标签: c#unity3d

解决方案


目前,您正在访问四元数的 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();
    }
}

推荐阅读