(五) 武器切换(使用技能)

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

/*
 * 战斗管理器 
 * 职能 : 仅负责战斗逻辑
 *       (开始、结束、暂停、加速、广告逻辑)
 * 核心玩法 :
 *       一局游戏大致3分钟,有三波敌人.
 *       一波普通攻击,
 *       一波大波攻击,
 *       最后一波boss攻击.
 *       敌人没被打死, 移动到屏幕外会自动循环,再次从出生点开始移动, 直到被打死.
 *       一波敌人全部被消灭,敌人才会开始第二波进攻.
 * 
**/

[System.Serializable]
public class BattleManager : MonoBehaviour 
{
    //内部属性
    //--------------------------------------------------------------------------

    // TODO:以后做成读取配置表
    public Transform[] enemyBirthTrans;                // 敌人出生点
    public Transform[] skillBirthTrans;                // 技能出生点
    public Transform leftTop;                          // 左上角位置
    public Transform rightBottom;                      // 右下角位置

    /** 记录当前第几波
     * 
     */
    private int wave = 1;

    /** 切换到下一波之前的准备时间,可以进行一些弹字等
     * 
     */
    private bool switching = false;
    private float switchDelta = 0f;
    private float switchTime = 2f;
    private LevelConfig currLevelConf;
    private Coroutine enemyCorotine;
    private Coroutine skillCorotine;

    // 本波敌人总数
    [SerializeFieldprivate int totalNum;


    //外部部属性
    //--------------------------------------------------------------------------
    public BattleConfs battleConfs
    public BattleDatas battleDatas;

    //内部方法
    //--------------------------------------------------------------------------


    /** 技能出生逻辑
  * 
  */
    private IEnumerator InvokeSkill(int curentWave)
    {
        Debug.LogError("curentWave; " + curentWave);

        int num = 0;
        string id = "";
        switch (curentWave)
        {
            case 1:
                id = currLevelConf.skill1Id;
                num = currLevelConf.GetInt(currLevelConf.skill1Num);
                break;
            case 2:
                id = currLevelConf.skill2Id;
                num = currLevelConf.GetInt(currLevelConf.skill2Num);
                break;
            case 3:
                id = currLevelConf.skill3Id;
                num = currLevelConf.GetInt(currLevelConf.skill3Num);
                break;
            default:
                break;
        }

        totalNum = num;

        yield return new WaitForSeconds(3f);

        while (num > 0)
        {
       
            int index = Random.Range(0enemyBirthTrans.Length);

            battleDatas.CreateSkill(idenemyBirthTrans[index].positionQuaternion.identity);

            Debug.LogError("num; " + num);


            yield return new WaitForSeconds(2f);
            num--;
        }


    }

    /** 停止出生敌人
     * 
     */
    private void StopInvokeSkill()
    {
        if (skillCorotine != null)
        {
            StopCoroutine("InvokeSkill");
            skillCorotine = null;

            //Debug.LogError("StopCoroutine");
        }
    }


    /** 敌人出生逻辑
     * 
     */
    private IEnumerator InvokeEnemy(int curentWave)
    {
        Debug.LogError("curentWave; " + curentWave);

        int num = 0;
        string id = "";
        switch (curentWave)
        {
            case 1:
                id = currLevelConf.enemy1Id;
                num = currLevelConf.GetInt(currLevelConf.enemy1Num);
                break;
            case 2:
                id = currLevelConf.enemy2Id;
                num = currLevelConf.GetInt(currLevelConf.enemy2Num);
                break;
            case 3:
                id = currLevelConf.enemy3Id;
                num = currLevelConf.GetInt(currLevelConf.enemy3Num);
                break;
            default:
                break;
        }

        totalNum = num;

        yield return new WaitForSeconds(1f);

        while (num > 0)
        {
            //battleDatas.CreateEnemy(id, new Vector3(0, 4f, 0), Quaternion.identity);

            int index = Random.Range(0enemyBirthTrans.Length);

            battleDatas.CreateEnemy(idenemyBirthTrans[index].positionQuaternion.identity);

            Debug.LogError("num; " + num);


            yield return new WaitForSeconds(2f);
            num--;
        }


    }

    /** 停止出生敌人
     * 
     */
    private void StopInvokeEnemy()
    {
        if (enemyCorotine != null)
        {
            StopCoroutine("InvokeEnemy");
            enemyCorotine = null;

            //Debug.LogError("StopCoroutine");
        }
    }


    /** 敌人产生
    * 
    */
    private void OnWaveStart(int currentWave)
    {
        StopInvokeEnemy();
        //创建每一波敌人
        enemyCorotine = StartCoroutine("InvokeEnemy",currentWave);
    

        StopInvokeSkill();
        //创建每一波技能
        skillCorotine = StartCoroutine("InvokeSkill"currentWave);
    }


   
    /** 玩家胜利
     * 
     */
    private void OnSucces()
    {
        StopInvokeEnemy();
        battleDatas.ClearBattleWave();

        GameMgr.instanse.Success();
    }

    //公开接口
    //--------------------------------------------------------------------------

    // 初始化战斗
    public void InitBattle(GlobleConfs globleConfsGlobleLocalData globleLocalData)
    {
        /** 加载战斗配置
         * 
         */
        battleConfs = new BattleConfs();
        battleConfs.Load();

        /** 初始化战斗数据
         * 
         */
        battleDatas = new BattleDatas();
        battleDatas.Reset();
        battleDatas.SetData(globleConfsglobleLocalDatabattleConfs);

        currLevelConf = globleConfs.GetConfById<LevelConfig>(globleLocalData.currentLevel.ToString(), globleConfs.GetLevelConfs());

        OnStart();
    }


    /** 开始游戏
      * 
      */
    public void OnStart()
    {
        //创建角色和敌人

        battleDatas.OnStart();

        OnWaveStart(wave);
        battleDatas.OnWaveStart(wave);

        battleDatas.CreateRole(currLevelConf.playerIdVector3.zeroQuaternion.identity);
    }

    /** 每帧更新
      * GameMgr 驱动此心跳
      * 
      */
    public void OnUpdate(float deltaTime)
    {
        if (GameMgr.instanse.Battling() == falsereturn;

        if(battleDatas.EnemyAllDeath(totalNum))
        {
            if(switching == false)
            {
                if(wave == 3
                {
                    
                    Debug.LogError("success!");

                    OnSucces();

                } else {
                    
                    switching = true;
                    wave++;

                    battleDatas.ClearBattleWave();
                }

            } else {
                if(switchDelta > switchTime)
                {
                    switchDelta = 0f;
                    switching = false;

                    OnWaveStart(wave);
                    battleDatas.OnWaveStart(wave);

                } else {
                    
                    switchDelta += deltaTime;
                }
            }
        }
        else
        {
            battleDatas.OnUpdate(deltaTime);
        }
    }

    //公开接口
    //--------------------------------------------------------------------------

    /** 收否出界
     *  左右下方判断,上方不用判断
     * 
     */
    public bool IsOutSide(Vector3 pos)
    {
        if (pos.x < leftTop.position.x)
            return true;

        if (pos.x > rightBottom.position.x)
            return true;

        if (pos.y < rightBottom.position.y)
            
            return true;
        
        return false;
    }

    /** 矫正出界点
     * 
     */
    public Vector3 CorrectOutSide(Vector3 pos)
    {
        return new Vector3(pos.xleftTop.position.y0);
    }

}
 

 

 

 

using UnityEngine;
using Excel;
using System.Data;
using System.IO;
using System.Collections.Generic;
using OfficeOpenXml;
using UnityEditor;


// TODO:重构
public static class ExcelTool
{
    //TODO:内部方法
    //--------------------------------------------------------------------------

    // 定义数组
   
    // 关卡配置
    // ID: 1-10  
    static string[,] levels = new string[,]
    {
        {   "id","playerId",
            "enemy1Id","enemy1Num","skill1Id","skill1Num""obstacles1Id","obstacles1Num",
            "enemy2Id","enemy2Num","skill2Id","skill2Num","obstacles2Id","obstacles2Num",
            "enemy3Id","enemy3Num","skill3Id","skill3Num","obstacles3Id","obstacles3Num",
        },
        {   "1","10010001",
            "10010002","1","50010001","2""obstacles1Id","obstacles1Num",
            "10010002","3","50010001","4","obstacles2Id","obstacles2Num",
            "10010002","5","50010001","6","obstacles3Id","obstacles3Num",
        },
    };

    // 角色配置
    // ID: 1001  
    static string[,] roles = new string[,]
    {
        { "id","prefab","moveAiId","weaponAiId","roleType","maxHP""moveSpeed"},
        { "10010001","role1","","40010001","1","1000",""},                      //玩家不需要移动ai,和 初始移动速度
        { "10010002","role2","20010001","40010001","2","50","1"},
    };


    // 移动ai配置
    // ID: 2001  
    static string[,] moveAIs = new string[,]
    {
        { "id","aiName"},
        { "20010001","SingleForwardAI"},
    };

    // 子弹配置
    // ID: 3001 
    static string[,] bullets = new string[,] 
    {
        { "id","prefab","moveAiId","attack","explosionEffect","hitEffect""fireEffect""moveSpeed"},
        { "30010001","bullet1","20010001","15","explosionEffect","hitEffect""fireEffect""5"},
    };

    // 武器配置
    // ID: 4001  
    static string[,] weapons = new string[,] 
    {
        { "id","aiName""shootInterval","bulletID"},
        { "40010001","SingleShootAI""0.2" ,"30010001"},
    };

    // 技能配置
    // ID: 5001 
    static string[,] skills = new string[,]
    {
        { "id","prefab","moveAiId","weaponAiId","moveSpeed","lifeTime"},
        { "50010001","bullet1","20010001","40010001""5","3"},
    };


    // 向Excel写配置数据(数组)
    //--------------------------------------------------------------------------

    static void WriteConfigTable(ExcelWorksheet worksheetstring[,] contents)
    {
        int rowCount = contents.GetLength(0);
        int colCount = contents.GetLength(1);

        for (int i = 0i < rowCounti++)
        {
            for (int j = 0j < colCountj++)
            {
                var v = contents[ij];
                worksheet.Cells[i + 1j + 1].Value = v;
            }
        }
    }


    static void TryWriteConfig(ExcelWorksheet worksheetstring sheetName)
    {
        if (sheetName == GlobleStr.LevelConf)
 
            WriteConfigTable(worksheetlevels);

        else if (sheetName == GlobleStr.RoleConf)
            
            WriteConfigTable(worksheetroles);
        
        else if (sheetName == GlobleStr.MoveAiConf)

            WriteConfigTable(worksheetmoveAIs);

        else if (sheetName == GlobleStr.WeaponConf)

            WriteConfigTable(worksheetweapons);

        else if (sheetName == GlobleStr.BulletConf)

            WriteConfigTable(worksheetbullets);

        else if (sheetName == GlobleStr.SkillConf)

            WriteConfigTable(worksheetskills);
    }


    //--------------------------------------------------------------------------
    // 读取 Excel ; 需要添加 Excel.dll; System.Data.dll;
    // excel文件名
    // sheet名称
    // DataRow的集合

    static DataRowCollection TryReadExcel(string excelNamestring sheetName)
    {
        DataSet result = ReadExcel(excelName);

        return result.Tables[sheetName].Rows;
    }

    static DataSet ReadExcel(string excelName)
    {
        string path = Application.dataPath + "/" + excelName;
        FileStream stream = File.Open(pathFileMode.OpenFileAccess.ReadFileShare.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet result = excelReader.AsDataSet();

        Debug.Log("path: " + path);
        Debug.Log("result: " + result.Tables.Count);
        Debug.Log("excelReader: " + excelReader.ResultsCount);

        return result;
    }

    static int GetFieldId(DataRowCollection collectstring fieldName)
    {
        // 标题名称
        var titles = collect[0];
        for (int j = 0j < titles.ItemArray.Lengthj++)
        {
            var title = titles[j];
            if(title.ToString() == fieldName)
            return j;
        }
        return -1;
    }



    //TODO:外部接口
    //--------------------------------------------------------------------------

    // 从Excel读配置数据(反射)
    public static List<TReadConfigTable<T>(string excelNamestring sheetNamewhere T:CCObj,new()
    {
        List<Tlist = new List<T>();

        DataRowCollection collect = TryReadExcel(excelNamesheetName);
        if (collect.Count == 0return null;

        //Debug.Log("collect.Count : " + collect.Count);

        // i 从1开始读取数据,0行是表头
        for (int i = 1i < collect.Counti++)
        {
            if (collect[i][0].ToString() == ""continue;

            T t = new T();
            var fields = t.getFieldNames();

            //Debug.Log("fields.Length : " + fields.Length);

            for (int j = 0j < fields.Length;j++)
            {
                var fieldName = fields[j];
                int id = GetFieldId(collectfieldName);
                var val = collect[i][id];
                t.setValue(fields[j], val);

                //Debug.Log("field : " + fields[j]);
                //Debug.Log("index : " + id);
                //Debug.Log("field val : " + val);
            }

            list.Add(t); 
        }

        return list;
    }


    // 写入 Excel , 需要添加 OfficeOpenXml.dll
    // excel 文件名
    // sheet 名称

    public static void WriteExcel(string excelNamestring sheetName)
    {
        //自定义excel的路径
        string path = Application.dataPath + "/" + excelName;
        FileInfo newFile = new FileInfo(path);

        if (newFile.Exists)
        {
            Debug.Log("exists");


            DataSet result = ReadExcel(excelName);
            var oldSheet = result.Tables[sheetName];

            foreach(var v in result.Tables)
            {
                Debug.Log("v: " + v);
            }

            Debug.Log("oldSheet Contains: " + result.Tables.Contains(sheetName));
            Debug.Log("oldSheet: " + oldSheet);

            if (oldSheet != null) {
                ExcelPackage package = new ExcelPackage(newFile);
                package.Workbook.Worksheets.Delete(sheetName);
                //保存excel
                package.Save();
                AssetDatabase.Refresh();

                Debug.Log("delete sheetName: " + sheetName);
            }
        }
        else
        {
            Debug.Log("not exists");
            //创建一个新的excel文件
            newFile = new FileInfo(path);
        }

        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
          
            //在excel空文件添加新sheet
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);

            TryWriteConfig(worksheetsheetName);

            //保存excel
            package.Save();
            AssetDatabase.Refresh();

            Debug.Log("save");
        }
    }
}

 

 

 

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


/**
 * 运行时数据 
 * 职能: 管理(增、删、改、查操作) 角色、敌人、技能、金币 等游戏对象
 * 
 * 玩家   controller
 * 敌人   controller   (数组)
 * 技能   controller   (数组)
 * 障碍物  controller   (数组)
 * 子弹移动ai   (数组, 子弹会持有发射源的controller, 攻击目标的transform, 子弹有个碰撞检测脚本)
 *   
 * 
 * 
**/

[System.Serializable]
public class BattleDatas
{
    //内部属性
    //--------------------------------------------------------------------------
    GlobleLocalData globleLocalData;
    GlobleConfs globleConfs;
    BattleConfs battleConfs;

    // 敌人引用
    [SerializeFieldList<EnemyCtrenmeyCtrs;
    // 子弹引用
    [SerializeFieldList<BulletCtrbulletCtrs;
    // 子弹引用
    [SerializeFieldList<SkillCtrskillCtrs;
    // 玩家引用
    [SerializeFieldRoleCtr roleCtr;
    // 本波死亡敌人总数
    [SerializeFieldint deathNum;




    //内部方法
    //--------------------------------------------------------------------------

    /** 玩家 (不需要移动ai,仅加载攻击ai)
     * 
     */
    private T CreateRoleCommon<T>(RoleConfig confVector3 posQuaternion rotwhere T : PlayerCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefabposrot);

        // 添加武器ai
        var weaponConf = battleConfs.GetConfById<WeaponConfig>(conf.weaponAiIdbattleConfs.GetWeaponConfs());
        var weaponAI = obj.AddComponent(GlobalFunction.GetTypeByClassName(weaponConf.aiName)) as ShootBaseAI;

        // 添加controller
        var ctr = obj.AddComponent(typeof(T)) as T;

        ctr.SetConfig(confweaponConf);
        ctr.SetWeaponAI(weaponAI);

        ctr.IsEnemy = false;

        return ctr;
    }

    /** 敌人 (加载移动ai, 攻击ai)
     * 
     */
    private T CreateEnemyCommon<T>(RoleConfig confVector3 posQuaternion rotwhere T : PlayerCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefabposrot);

        // 添加移动ai
        var moveConf = battleConfs.GetConfById<MoveAIConfig>(conf.moveAiIdbattleConfs.GetMoveAIConfs());
        var moveAI = obj.AddComponent(GlobalFunction.GetTypeByClassName(moveConf.aiName)) as BaseAI;

        // 添加武器ai
        var weaponConf = battleConfs.GetConfById<WeaponConfig>(conf.weaponAiIdbattleConfs.GetWeaponConfs());
        var weaponAI = obj.AddComponent(GlobalFunction.GetTypeByClassName(weaponConf.aiName)) as ShootBaseAI;

        // 添加controller
        var ctr = obj.AddComponent(typeof(T)) as T;

        ctr.SetConfig(confweaponConf);
        ctr.SetMoveAI(moveAI);
        ctr.SetWeaponAI(weaponAI);

        ctr.IsEnemy = true;

        return ctr;
    }

    /** 创建子弹(加载移动ai)
     * 
     */
    private T CreateBulletCommon<T>(BulletConfig confVector3 posQuaternion rotbool isEnemywhere T : BulletCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefabposrot);

        // 添加移动ai
        var moveConf = battleConfs.GetConfById<MoveAIConfig>(conf.moveAiIdbattleConfs.GetMoveAIConfs());
        var moveAI = obj.AddComponent(GlobalFunction.GetTypeByClassName(moveConf.aiName)) as BaseAI;

        // 添加controller
        var ctr = obj.AddComponent(typeof(T)) as T;

        ctr.SetMoveAI(moveAI);
        ctr.SetConfig(conf);

        ctr.IsEnemy = isEnemy;

        return ctr;
    }

    /** 创建技能(加载移动ai)
     * 
     */
    private T CreateSkillCommon<T>(SkillConfig confVector3 posQuaternion rotwhere T : SkillCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefabposrot);

        // 添加移动ai
        var moveConf = battleConfs.GetConfById<MoveAIConfig>(conf.moveAiIdbattleConfs.GetMoveAIConfs());
        var moveAI = obj.AddComponent(GlobalFunction.GetTypeByClassName(moveConf.aiName)) as BaseAI;

        // 添加controller
        var ctr = obj.AddComponent(typeof(T)) as T;

        ctr.SetMoveAI(moveAI);
        ctr.SetConfig(conf);

        return ctr;
    }

    /** 回收敌人
     * 
     */
    private void ClearEnemys()
    {
        for (int i = 0i < enmeyCtrs.Counti++)
        {
            enmeyCtrs[i] = null;
        }
        enmeyCtrs.Clear();
    }

    /** 回收子弹
     * 
     */
    private void ClearBullets()
    {

        for (int i = 0i < bulletCtrs.Counti++)
        {
            var obj = bulletCtrs[i];
            if (obj != null)
            {
                GameObject.Destroy(obj.gameObject);
            }

            bulletCtrs[i] = null;
        }
        bulletCtrs.Clear();
    }

    /** 回收技能
    * 
    */
    private void ClearSkills()
    {

        for (int i = 0i < skillCtrs.Counti++)
        {
            var obj = skillCtrs[i];
            if (obj != null)
            {
                GameObject.Destroy(obj.gameObject);
            }

            skillCtrs[i] = null;
        }
        skillCtrs.Clear();
    }


    //公开接口
    //--------------------------------------------------------------------------

    /** 重置
     * 
     */
    public void Reset()
    {
        roleCtr = null;
        enmeyCtrs = new List<EnemyCtr>();
        bulletCtrs = new List<BulletCtr>();
        skillCtrs = new List<SkillCtr>();
    }

    /** 初始化
     * 
     */
    public void SetData(GlobleConfs gConfsGlobleLocalData gLocalDataBattleConfs bConfs)
    {
        globleLocalData = gLocalData;
        globleConfs = gConfs;
        battleConfs = bConfs;
    }

    /** 开始游戏
      * 
      */
    public void OnStart()
    {
    }

    /** 每一波开始
     * 
     */
    public void OnWaveStart(int currentWave)
    {
        deathNum = 0;

    }


    /** 每帧更新
      * BattleManager 驱动此心跳
      * 
      */
    public void OnUpdate(float deltaTime)
    {

        roleCtr.OnUpdate(deltaTime);

        for (int i = 0i < enmeyCtrs.Count;i++)
        {
            enmeyCtrs[i].OnUpdate(deltaTime);
        }

        for (int i = 0i < bulletCtrs.Counti++)
        {
            bulletCtrs[i].OnUpdate(deltaTime);
        }

        for (int i = 0i < skillCtrs.Counti++)
        {
            skillCtrs[i].OnUpdate(deltaTime);
        }
    }
   

    /** 创建角色
     * 
     */
    public RoleCtr CreateRole(string roleIdVector3 posQuaternion rot)
    {
        var conf = battleConfs.GetConfById<RoleConfig>(roleIdbattleConfs.GetRoleConfs()); //currLevelConf.playerId

        var ctr = CreateRoleCommon<RoleCtr>(confposrot);
        ctr.OnStart();

        roleCtr = ctr;
            
        return ctr;
    }

    /** 创建敌人
     * 
     */
    public EnemyCtr CreateEnemy(string enemyIdVector3 posQuaternion rot)
    {
        var conf = battleConfs.GetConfById<RoleConfig>(enemyIdbattleConfs.GetRoleConfs());

        var ctr = CreateEnemyCommon<EnemyCtr>(confposrot);
        ctr.OnStart();

        enmeyCtrs.Add(ctr);

        return ctr;
    }


    /** 创建子弹
    * 
    *  isEnemy 是玩家还是敌人发射的
    */
    public BulletCtr CreateBullet(string bullectIDVector3 posQuaternion rotbool isEnemy)
    {
        var conf = battleConfs.GetConfById<BulletConfig>(bullectIDbattleConfs.GetBulletConfs());

        var ctr = CreateBulletCommon<BulletCtr>(confposrotisEnemy);
        ctr.OnStart();

        bulletCtrs.Add(ctr);

        return ctr;
    }

    /** 创建敌人
    * 
    */
    public SkillCtr CreateSkill(string skillIdVector3 posQuaternion rot)
    {
        var conf = battleConfs.GetConfById<SkillConfig>(skillIdbattleConfs.GetSkillConfs());

        var ctr = CreateSkillCommon<SkillCtr>(confposrot);
        ctr.OnStart();

        skillCtrs.Add(ctr);

        return ctr;
    }

    /** 距离参考者最近的技能
      *  
      */
    public EnemyCtr NearestSkill(Transform refer)
    {
        EnemyCtr ctr = null;
        float tempDis = float.MaxValue;
        float dis;
        foreach (var v in enmeyCtrs)
        {
            dis = Vector3.Distance(refer.positionv.transform.position);
            if (tempDis > dis)
            {
                tempDis = dis;
                ctr = v;
            }
        }

        return ctr;
    }

    /** 距离参考者最近的敌人
     *  
     */
    public EnemyCtr NearestEnemy(Transform refer)
    {
        EnemyCtr ctr = null;
        float tempDis = float.MaxValue;
        float dis;
        foreach(var v in enmeyCtrs)
        {
            dis = Vector3.Distance(refer.positionv.transform.position);
            if(tempDis > dis)
            {
                tempDis = dis;
                ctr = v;
            }
        }

        return ctr;
    }


    /** 距离参考者最近的玩家
     *  
     */
    public RoleCtr NearestPlayer(Transform refer)
    {
        return roleCtr;
    }

    /** 掉血
     * 
     */
    public void CutHp(PlayerCtrBase roleint dhp)
    {
        role.GetData().CutHP(dhp);
    }

    /** 切换到技能
      * 
      * 实质上是切换武器ai
      * 
      */
    public void SwitchToSkill(PlayerCtrBase ctrSkillConfig skillConf)
    {
        var oldWeaponAI = ctr.gameObject.GetComponent(typeof(ShootBaseAI));
        if(oldWeaponAI!= null)
        {
            GameObject.Destroy(oldWeaponAI);
        }

        // 添加武器ai
        var newWeaponConf = battleConfs.GetConfById<WeaponConfig>(skillConf.weaponAiIdbattleConfs.GetWeaponConfs());
        var newWeaponAI = ctr.gameObject.AddComponent(GlobalFunction.GetTypeByClassName(newWeaponConf.aiName)) as ShootBaseAI;

        ctr.ReSetWeaponConfig(newWeaponConfskillConf.GetFloat(skillConf.lifeTime));
        ctr.SetWeaponAI(newWeaponAI);
    }

    /** 玩家角色死亡
     * 
     */
    public void RoleDeath(RoleCtr role)
    {
        if(role == roleCtr)
        {
            //roleCtr.IsDead = true;
            roleCtr = null;
        }
    }

    /** 敌人死亡
     * 
     */
    public void EnemyDeath(EnemyCtr enemy)
    {
        if(enmeyCtrs.Contains(enemy))
        {
            //enemy.IsDead = true;

            deathNum++;

            GameObject.Destroy(enemy.gameObject);

            enmeyCtrs.Remove(enemy);


  
        }
    }

    /** 敌人是否全部消灭
     *  用来判断下一波进行何时进行
     *  或者比赛胜利
     * 
     */
    public bool EnemyAllDeath(int totalNum)
    {
        return deathNum == totalNum;
    }

    /** 清理上一波数据
     * 
     */
    public void ClearBattleWave()
    {
        ClearEnemys();
        ClearBullets();
    }
}
 

 

 

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

/** 玩家控制器
 *  持有武器的引用,负责角色行为逻辑(攻击、移动)
 * 
 * 
 *  玩家不做碰撞检测,检测为单向,敌人、技能、子弹等负责检测碰撞
 * 
 * 
 */

[System.Serializable]
public class RoleCtr : PlayerCtrBase 
{
    //内部属性
    //--------------------------------------------------------------------------
    Vector3 lastPosition_;     // 上次位置
    Vector3 clickPosition_;    // 点击位置

    //内部方法
    //--------------------------------------------------------------------------
    /** 玩家操作 滑动(或者点击鼠标)
     * 
     */
    private bool IsOperating()
    {

#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE
        if (Input.GetMouseButton(0))
        {
            return true;
        }
#elif UNITY_ANDROID || UNITY_IPHONE
        if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved){
            return true;
        }
#endif

        return false;
    }

    // z轴为10 : 是摄像机z轴取相反数
    private Vector3 GetPosition()
    {
        Vector3 v = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0f0f10f));
        return v;
    }

    /** 角色移动
     * 
     */
    private void UpdateMove(float deltaTime)
    {
        lastPosition_ = transform.position;     //存储上一次位置

        clickPosition_ = GetPosition();

        transform.position = clickPosition_;
    }

    /** 更新武器攻击时间、执行攻击行为
     * 
     */
    private void UpdateWeapon(float deltaTime)
    {
        this.weaponAI.OnUpdate(deltaTime);
    }

    /** 仅更新武器攻击时间、不执行攻击行为
    * 
    */
    private void UpdateWeaponTimeOnly(float deltaTime)
    {
        this.weaponAI.OnUpdateTimeOnly(deltaTime);
    }


    //override方法
    //--------------------------------------------------------------------------

    public override void OnStart()
    {
        object[] args = { thisthis.transformthis.weaponConf};

        this.weaponAI.OnStart(args);

        base.OnStart();
    }

    /** 每帧更新
      *  BattleDatas 驱动此心跳
      * 
      */
    public override void OnUpdate(float deltaTime
    {
        base.OnUpdate(deltaTime);

        if (IsOperating())
        {

            //Debug.LogError("IsOperating deltaTime: " + deltaTime);

            UpdateMove(deltaTime);
            UpdateWeapon(deltaTime);
        } 
        else
        {
            //Debug.LogError("UpdateWeaponTimeOnly: " + deltaTime);

            UpdateWeaponTimeOnly(deltaTime);
        }
    }

    //公开接口
    //--------------------------------------------------------------------------



}

 

 

 

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

/** 角色、敌人的controller
 * 负责 :
 * 初始化对象的配置、记录对象运行数据、动画控制器、移动ai引用、
 * 武器ai引用、子弹数组引用等.
 * (controller :  config、data、animator、移动ai引用、武器ai引用、子弹ai引用(数组) 等)
 * 
 **/

public class PlayerCtrBase : CtrBase
{
    //内部属性
    //--------------------------------------------------------------------------
    [SerializeFieldprotected WeaponConfig tempWeaponConf;  // 武器配置(技能等意外获得武器)
    [SerializeFieldprotected float skillTime;              // 技能生效时间
    [SerializeFieldprotected float skillDelta;             //
    [SerializeFieldprotected bool skilling = false;        // 技能生效中

    [SerializeFieldprotected WeaponConfig weaponConf;  // 武器配置
    [SerializeFieldprotected RoleConfig conf;          // 角色配置
    [SerializeFieldprotected RoleData data;            // 角色数据
    [SerializeFieldprotected BaseAI moveAI;            // 移动脚本
    [SerializeFieldprotected ShootBaseAI weaponAI;     // 武器脚本 (使用技能能,换成技能脚本)

    protected bool isEnemy = false;
    protected bool isStart = false;

    //内部方法
    //--------------------------------------------------------------------------

    /** 碰撞检测
    * 
    */
    protected virtual void CollisionDetection() { }


    //override方法 
    //--------------------------------------------------------------------------

    /** 技能生效
     * 
     */
    public virtual void OnSkillStart()
    {
        object[] args = { thisthis.transformthis.tempWeaponConf };

        this.weaponAI.OnStart(args);

        OnStart();

        this.skilling = true;
    }

    /**
     * 
     */
    public virtual void OnStart()
    {
        battle = GameMgr.instanse.BattleMgr();

        isStart = true;
    }

    /** 每帧更新
     *  BattleDatas 驱动此心跳
     * 
     */
    public virtual void OnUpdate(float deltaTime)
    {
        if (this.data == nullreturn;
        if (this.conf == nullreturn;
        if (isStart == falsereturn;

        // 碰撞检测
        this.CollisionDetection();

        // 技能倒计时
        if (this.skilling == true) {
            if(this.skillDelta > this.skillTime)
            {

                Debug.LogError("技能失效 ");

                this.skilling = false;

                // 技能失效,恢复初始武器
                this.OnStart();
            } else {
                this.skillDelta += deltaTime
            }
        }
               
    }



    //公开接口
    //--------------------------------------------------------------------------

    /** 切换武器时,临时武器配置
     * 
     */
    public void ReSetWeaponConfig(WeaponConfig wcfloat time)
    {
        this.tempWeaponConf = wc;
        this.skillTime = time;
        this.skillDelta = 0f;

        this.OnSkillStart();
    }

    /** 初始化 config 和 data(血量最大值等)
     * 
     */
    public void SetConfig(RoleConfig cWeaponConfig wc)
    {
        this.conf = c;
        this.weaponConf = wc;

        this.data = new RoleData();
        this.data.SetData(c.GetInt(c.maxHP));
    }

    /** 移动ai
     * 
     */
    public void SetMoveAI(BaseAI move)
    {
        this.moveAI = move;
    }

    /** 武器ai
     * 
     */
    public void SetWeaponAI(ShootBaseAI weapon)
    {
        this.weaponAI = weapon;
    }

    /** 是玩家还是敌人
     * 
     */
    [SerializeFieldprotected bool enemy;
    public bool IsEnemy
    {
        set { this.enemy = value; }
        get { return this.enemy; }
    }

    /** 死亡标记
     * 
     */
    [SerializeFieldprotected bool dead;
    public bool IsDead
    {
        set { this.dead = value; }
        get { return this.dead; }
    }

    /** 角色数据(血量)
     * 
     */
    public RoleData GetData()
    {
        return data;
    }

}
 

 

 

 

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

/** 技能控制器
 * 
 *  更新技能移动ai
 *  
 *  碰撞检测
 *
 *
 */


[System.Serializable]
public class SkillCtr : SkillCtrBase
{
    //内部属性
    //--------------------------------------------------------------------------


    //内部方法
    //--------------------------------------------------------------------------
    /** 碰撞检测
    *   子弹ctr 有个属性IsEnemy,标记子弹是玩家还是敌人发出的.
    *   如果是玩家发出的,子弹会检测所有敌人.
    *   如果是敌人发出的,子弹会检测所有玩家.
    * 
    * 
    */
    protected override void CollisionDetection()
    {
        // 检测玩家
        var player = battle.battleDatas.NearestPlayer(transform);

        if(player == null)
        {
            Debug.LogError("没有检测到玩家");

            return;
        }
        bool inScope = GlobalFunction.InFieldOfVision(player.transform.positiontransform.position);
        if (inScope)
        {
            Debug.LogError("玩家获得技能 " + player.gameObject.name);

            battle.battleDatas.SwitchToSkill(playerthis.skillConf);

        } 
    }

    //override方法
    //--------------------------------------------------------------------------
    /** BattleDatas 创建时,完成初始化(OnStart)
     * 
     */
    public override void OnStart()
    {
        var moveDir =  Vector3.down;
        object[] args = { this.transform ,this.skillConf.moveSpeedmoveDirnull};

        this.moveAI.OnStart(args);

        base.OnStart();
    }

    //公开接口
    //--------------------------------------------------------------------------

 

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值