统一添加声音

时间:2016-05-30 17:11:26

标签: c# unity3d

声音没有播放第二次触摸它只播放第一次触摸声音只有0.02持续时间它在mp3中它只播放第一次触摸但我必须为每次点击它,它应该感觉像加速器

    using UnityEngine;
    using System.Collections;
    public class Player : MonoBehaviour 
    {
        // The force which is added when the player jumps
        // This can be changed in the Inspector window
    public Vector2 jumpForce = new Vector2(0, 300);
    public AudioClip imp;
        public AudioSource clk;
        // Update is called once per frame
        void Update ()
        {
            // Jump
            if (Input.GetMouseButtonDown(0))
            {

                GetComponent<Rigidbody2D>().velocity = Vector2.zero; 
                GetComponent<Rigidbody2D>().AddForce(jumpForce);
                clk.PlayOneShot (imp, 0.7f);

            }
            Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
            if (screenPosition.y > Screen.height || screenPosition.y < 0)
            {
                Die();
            }
        }

        // Die by collision
        void OnCollisionEnter2D(Collision2D other)
        {
            Die();
        }


        void Die()
        {

            Application.LoadLevel(0);

        }
    }

1 个答案:

答案 0 :(得分:1)

第二次触摸时没有播放声音,因为Input.GetMouseButtonDown(0)只会检测到一次触摸。循环浏览Touches然后播放声音(如果按下)。在检测到第一次触摸后断开循环,因为当屏幕上有触摸时,您只能播放一个声音。

void Update()
{
    int touches = Input.touchCount;
    Debug.Log(touches);

    for (int i = 0; i < touches; i++)
    {
        if (touches > 0 && Input.GetTouch(i).phase == TouchPhase.Began)
        {
            clk.PlayOneShot(imp, 0.7f);
            break;
        }
    }

    if (Input.GetMouseButtonDown(0))
    {

        GetComponent<Rigidbody2D>().velocity = Vector2.zero;
        GetComponent<Rigidbody2D>().AddForce(jumpForce);
    }
    Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
    if (screenPosition.y > Screen.height || screenPosition.y < 0)
    {
        Die();
    }
}