unity 2d 入门 飞翔小鸟 音效(十五)

1、玩家脚本 添加碰撞、飞翔音效

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Fly : MonoBehaviour
{
    
    
    //获取小鸟(刚体)
    private Rigidbody2D bird;
    //速度
    public float speed;
    //跳跃
    public float jump;
    //是否存活
    public static bool life = true;
    //获取动画器
    private Animator animator;
    //结束图片
    private GameObject gameOver;
    //结束跳转时间
    private float time;
    //音频源(飞翔)
    private AudioSource audioSource;
    //死亡音效
    public AudioClip dieClip;

    // Start is called before the first frame update
    void Start()
    {
    
    
        bird = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        gameOver = GameObject.Find("Canvas/Image");
        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
    
    
        //存活的时候才能运动
        if (life)
        {
    
    
            bird.velocity = new Vector2(speed, bird.velocity.y);
            //鼠标点击
            if (Input.GetMouseButtonDown(0))
            {
    
    
                //点击鼠标播放音频源
                audioSource.Play();
                //鼠标点击给目标一个纵向速度
                bird.velocity = new Vector2(bird.velocity.x, jump);
            }
        }
        else {
    
    
            time += Time.deltaTime;
            if (time>=3) {
    
    
                FadeInOut.SwitchScene("start");
            }
        }
        //当触碰到死亡的时候出现
        gameOver.SetActive(!life);
    }
    //如果碰撞器撞到了某个物体
    private void OnCollisionEnter2D(Collision2D collision)
    {
    
    
        if (life==true) {
    
    
            Bling.blinking();
            audioSource.clip = dieClip;
            audioSource.Play();
        }
        life = false;
        animator.SetBool("life", false);
    }
}

在这里插入图片描述

2、在玩家添加音频源

添加组件->音频->选择音频源
把飞翔音效拖拽进去
勾选掉唤醒时候播放
在这里插入图片描述

3、在player脚本中把死亡音效拖拽进去

在这里插入图片描述
#4、添加得分音效
在柱子添加音频
在这里插入图片描述

5、柱子得分音效脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
    
    
    public static int score = 0;
    private Text scoreText;
    private bool isAdd=false;
    //得分音频源
    private AudioSource audioSource;
    // Start is called before the first frame update
    void Start()
    {
    
    
        scoreText = GameObject.Find("Canvas/score").GetComponent<Text>();
        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
    
    
        
    }

    private void OnGUI()
    {
    
    
        scoreText.text = score.ToString();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
    
    
        Debug.Log("触发");
        if (!isAdd){
    
    
            score++;
            audioSource.Play();
        }
        isAdd = true;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43205308/article/details/134908993
今日推荐