Unity3d打飞机(四)敌机移动与触碰效果,和爆炸音效

分类栏目:unity3d教程

161

Unity3d打飞机(四)敌机移动与触碰效果,和爆炸音效

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
//枚举
public enum DownType{
	Small,Middle,Big,SuperBullet,Bomb
}
//敌机移动
public class EnemyAndSuperMove : MonoBehaviour {
 
	//设定枚举类型
	public DownType type = DownType.Small;
	//下落时间
	private float downTime = 5f;
 
	//血量
	public int HP = 1;
 
	//敌机是否爆炸
	private bool isBomb = false;
 
	//爆炸图片切换
	private SpriteRenderer reder;
	public Sprite[] EnemySprite;
 
	//爆炸时间
	private float bombTime;
 
 
	//被打图片切换
	public Sprite[] hitSprite;
	//被打图片切换间隔
	private float hitTime;
 
	//分数
	public static int num = 0;
 
	//爆炸音效
	private AudioSource audioSource;
 
	// Use this for initialization
	void Start () {
		reder = GetComponent<SpriteRenderer> ();
		audioSource = GetComponent<AudioSource> ();
	}
	
	// Update is called once per frame
 
	void Update () {
		//敌机移动并销毁超出屏幕的
		transform.Translate (Vector3.down * downTime * Time.deltaTime);
		if (transform.position.y < -4.5) {
			Destroy (gameObject);
		}
 
		//判断敌机是否爆炸
		if (isBomb) {
			bombTime += Time.deltaTime;
			int bt = (int)(bombTime / (1f / 10));
			if (bt >= EnemySprite.Length) {
				Destroy (gameObject);
				num++;
				ButtonAndText.num = num;
				isBomb = false;
			} else {
				reder.sprite = EnemySprite [bt];
			}
 
		} else {
			//判断是否为中和大飞机,实现被打图片切换
			if ((type == DownType.Middle || type == DownType.Big ) && hitTime > 0) {
				hitTime -= Time.deltaTime;
				int hs = (int)(hitTime / (1f / 10)) % 2;
				reder.sprite = hitSprite [hs];
			}
		}
	}
 
	//触发器
	void OnTriggerEnter2D(Collider2D other){
		
		if (other.tag == "Bullet" && (type != DownType.SuperBullet || type != DownType.Bomb)) { //判断是不是碰到子弹
			SubtractHP ();
		} else if (other.tag == "hero") { //判断是否触碰到飞机
			if (type == DownType.SuperBullet || type == DownType.Bomb) {//判断是不是空投触碰到敌机
				Destroy (gameObject);
			} 
		}
 
	}
 
	//减血
	void SubtractHP(){
		HP--;
		hitTime = 0.2f;
		if (HP < 0) {
			Destroy (gameObject.GetComponent<Rigidbody2D>());			
			//播放爆炸音效
			audioSource.Play ();
			EnemyBomb ();
		}
	}
 
	//挂掉
	public void EnemyBomb(){		
		isBomb = true;
 
	}
 
}