Unity3D-塔防游戏项目主要源码(防御塔脚本)

using UnityEngine;
using System.Collections;

namespace TowerDefenceTemplate
{
    public class Tower : MonoBehaviour
    {
        public enum TowerType//防御塔类型
        {
            LightGun,//光速炮
            RocketLauncher,//火箭发射器
            FlameThrower//火焰喷射器
        };

        public TowerType towerType;//实例化防御塔类型

        public int
            Cost,//建一个塔所花费的金币数
            UpgradeCost;//升级一个塔所花费的金币数

        [HideInInspector]
        public int Level;//炮塔等级

        public int[]
            Range,//炮塔的攻击范围
            Damage;//伤害值

        public string TowerName;//炮塔的名字

        public GameObject
            Body,//炮塔的身体
            Head;//炮头

        public EllipsoidParticleEmitter
            Fire1,//2种粒子特效
            Fire2,
            Flame;//喷火特效

        private float Timer;//定义计时器

        private GameManager gameManager;//实例化GameManager对象

        private GameObject CurrentTarget;//定义当前的攻击目标

        public Transform
            GunPoint1,//2个射击点
            GunPoint2,
            DetectCircle;//侦查圈

        void Start()
        {
            gameManager = FindObjectOfType();//获取脚本
            DetectCircle.localScale = new Vector3(Range[Level], DetectCircle.localScale.y, Range[Level]);//炮塔等级不同,检测范围不同
            if (gameManager == null)
            {
                Debug.LogError("GameManager not found!");
                enabled = false;
            }
        }

        void OnMouseUp()
        {
            DetectCircle.gameObject.SetActive(true);//激活检测器所在的游戏对象
            gameManager.ActivateTowerControl(this);
        }

        void Update()
        {
            if (transform.parent == null)//如果没有父物体
            {
                return;//结束当前方法
            }
            float _detectRange = DetectCircle.localScale.x / 2;//侦测范围在X方向缩小一半
            Timer = Mathf.MoveTowards(Timer, 0, Time.deltaTime);//从当前时刻按秒数趋向0
            if (CurrentTarget == null)//如果当前目标为空
            {
                SearchTarget();//搜索目标
            }
            if (CurrentTarget != null)//如果当前目标非空
            {
                Vector3 ProjectionOnGround = new Vector3(CurrentTarget.transform.position.x, transform.position.y, CurrentTarget.transform.position.z);//定义目标点位置
                if (Vector3.Distance(transform.position, ProjectionOnGround) > _detectRange || CurrentTarget.tag == "Dead")//如果目标已出侦查范围或者目标已阵亡
                {
                    CurrentTarget = null;//把目标设为空
                    return;//结束当前方法
                }
                Vector3 ThisPosition = transform.position;//记录当前位置信息
                Quaternion TargetBodyRotation = Quaternion.LookRotation(new Vector3(CurrentTarget.transform.position.x, ThisPosition.y, CurrentTarget.transform.position.z) - transform.position, transform.up);//定义四元数做炮座旋转
                Quaternion TargetHeadRotation = Quaternion.LookRotation(CurrentTarget.transform.position - Head.transform.position, transform.up);//定义四元数做炮头旋转
                Body.transform.rotation = Quaternion.RotateTowards(Body.transform.rotation, TargetBodyRotation, Time.deltaTime * 100);//以自身y轴为轴,让身体做旋转
                Head.transform.rotation = Quaternion.RotateTowards(Head.transform.rotation, TargetHeadRotation, Time.deltaTime * 50);//让炮塔头看着目标
                if (Quaternion.Angle(Head.transform.rotation, TargetHeadRotation) < 2)//如果炮头的旋转度数小于2时
                {
                    if (towerType == TowerType.LightGun)//如果塔的类型是光速炮
                    {
                        AttackingLightGun();//执行光速炮射击
                    }
                    if (towerType == TowerType.RocketLauncher)//如果塔的类型是火箭发射器
                    {
                        AttackingRocketLauncher();//执行火箭发射器攻击
                    }
                    if (towerType == TowerType.FlameThrower)//如果塔的类型是火焰喷射器
                    {
                        AttackingFlameThrower();//执行喷射火焰
                    }
                }
            }
            else
            {
                if (towerType == TowerType.FlameThrower)//当炮塔类型为火焰喷射器时
                {
                    StopFlaming();//停止喷射火焰
                }
            }
        }

        public void Upgrade()//炮塔升级
        {
            Level++;//等级提升
            DetectCircle.localScale = new Vector3(Range[Level], DetectCircle.localScale.y, Range[Level]);//侦测半径扩大一倍
            UpgradeCost *= 2;
        }

        void SearchTarget()//搜索目标
        {
            foreach (var item in gameManager.SpawnedEnemies)
            {
                Vector3 ProjectionOnGround = new Vector3(item.transform.position.x, transform.position.y, item.transform.position.z);//定义所有敌方战车的位置
                if (item.tag == "Plane" && towerType != TowerType.RocketLauncher)//如果敌方战车是飞机并且炮塔类型不是火箭发射器时
                {
                    continue;//查找下一个
                }
                if (Vector3.Distance(transform.position, ProjectionOnGround) < DetectCircle.localScale.x / 2)//如果敌方战车进入到炮塔的检测范围(检测圆的半径)
                {
                    CurrentTarget = item;//把此敌人设为攻击目标
                }
            }
        }

        void StopFlaming()//停止喷射火焰
        {
            Flame.emit = false;//喷射火焰粒子系统false
            gameManager.FlameThrowerSound.Stop();//停止喷火声效
        }

        void AttackingLightGun()//光速炮攻击
        {
            if (Timer == 0)//当计时器为 0时
            {
                Timer = 0.3f;//重新定值为0.3s
                ShootLightGun(GunPoint1);//两个炮筒同时射击
                ShootLightGun(GunPoint2);
                Fire1.Emit();//调用粒子系统作为子弹从炮口打出的特效
                Fire2.Emit();
                gameManager.LightGunShootSound.Play();//播放光速炮射击音效 
            }
        }

        void ShootLightGun(Transform gunpoint)//光速炮射击
        {
            Bullet _tempbul;//炮弹
            for (int i = 0; i < gameManager.BulletsPool.Count; i++)
            {
                if (!gameManager.BulletsPool[i].gameObject.activeSelf)
                {
                    _tempbul = gameManager.BulletsPool[i];//给炮弹实例化对象
                    _tempbul.target = CurrentTarget;//定义炮弹的目标为当前炮塔检测到的目标
                    _tempbul.Damage = Damage[Level];//炮弹的伤害值为当前等级的伤害值
                    _tempbul.gameObject.SetActive(true);//激活炮弹
                    _tempbul.transform.position = gunpoint.position;//炮弹位置为射击点gunpoint
                    _tempbul.transform.rotation = gunpoint.rotation;//炮弹的旋转度等于射击点的旋转度
                    break;//结束当前循环
                }
            }
            int random = Random.Range(0, 20);//生成0-19的随机整数
            if (random == 1)//1/20的概率播放
            {
                gameManager.RicochetSound1.Play();//射击子弹的声效
            }
            if (random == 10)
            {
                gameManager.RicochetSound2.Play();
            }
            if (random == 20)
            {
                gameManager.RicochetSound3.Play();
            }
        }

        void AttackingRocketLauncher()
        {
            if (Timer == 0)//当计时器减到0时
            {
                Timer = 2;//让计时器值为2
                StartCoroutine(ShootRocketLauncher());//开始协同程序
            }
        }

        IEnumerator ShootRocketLauncher()//枚举器  火箭发射器射击状态
        {
            Rocket _temproc;//导弹
            for (int i = 0; i < gameManager.RocketsPool.Count; i++)
            {
                if (!gameManager.RocketsPool[i].gameObject.activeSelf)//第一个炮筒的发射过程
                {
                    _temproc = gameManager.RocketsPool[i];//给导弹实例化对象
                    _temproc.Damage = Damage[Level];//导弹的伤害值为当前的等级伤害
                    _temproc.Target = CurrentTarget;//导弹的目标为当前检测到的目标
                    _temproc.gameObject.SetActive(true);//激活导弹
                    _temproc.transform.position = GunPoint1.position;//导弹的位置在射击点GunPoint1
                    _temproc.transform.rotation = GunPoint1.rotation;//导弹随射击点旋转
                    gameManager.RocketLaunchSound.Play();//发射导弹的音效播放
                    Fire1.Emit();//导弹喷火粒子系统打开
                    break;//结束当前循环
                }
            }
            yield return new WaitForSeconds(0.3f);//等待0.3s
            for (int i = 0; i < gameManager.RocketsPool.Count; i++)
            {
                if (!gameManager.RocketsPool[i].gameObject.activeSelf)//第二个炮筒的发射过程
                {
                    _temproc = gameManager.RocketsPool[i];
                    _temproc.Damage = Damage[Level];
                    _temproc.Target = CurrentTarget;
                    _temproc.gameObject.SetActive(true);
                    _temproc.transform.position = GunPoint2.position;
                    _temproc.transform.rotation = GunPoint2.rotation;
                    gameManager.RocketLaunchSound.Play();
                    Fire2.Emit();
                    break;
                }
            }
        }

        void AttackingFlameThrower()//喷火器攻击
        {
            Flame.emit = true;//喷火粒子系统调用
            CurrentTarget.SendMessage("GetDamage", Damage[Level] * Time.deltaTime);//得到持续性伤害
            if (!gameManager.FlameThrowerSound.isPlaying)//如果现在没有播放喷火声效
            {
                gameManager.FlameThrowerSound.Play();//打开声效
            }
        }
    }
}

你可能感兴趣的:(unity3d)