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;

// 本波敌人总数
    [SerializeField] private 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(0, enemyBirthTrans.Length);

battleDatas.CreateSkill(id, enemyBirthTrans[index].position, Quaternion.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(0, enemyBirthTrans.Length);

battleDatas.CreateEnemy(id, enemyBirthTrans[index].position, Quaternion.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 globleConfs, GlobleLocalData globleLocalData)
    {
        /** 加载战斗配置
         * 
         */
        battleConfs = new BattleConfs();
        battleConfs.Load();

/** 初始化战斗数据
         * 
         */
        battleDatas = new BattleDatas();
        battleDatas.Reset();
        battleDatas.SetData(globleConfs, globleLocalData, battleConfs);

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

OnStart();
    }

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

battleDatas.OnStart();

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

battleDatas.CreateRole(currLevelConf.playerId, Vector3.zero, Quaternion.identity);
    }

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

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.x, leftTop.position.y, 0);
    }

}

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 worksheet, string[,] contents)
    {
        int rowCount = contents.GetLength(0);
        int colCount = contents.GetLength(1);

for (int i = 0; i < rowCount; i++)
        {
            for (int j = 0; j < colCount; j++)
            {
                var v = contents[i, j];
                worksheet.Cells[i + 1, j + 1].Value = v;
            }
        }
    }

static void TryWriteConfig(ExcelWorksheet worksheet, string sheetName)
    {
        if (sheetName == GlobleStr.LevelConf)
 
            WriteConfigTable(worksheet, levels);

else if (sheetName == GlobleStr.RoleConf)
            
            WriteConfigTable(worksheet, roles);
        
        else if (sheetName == GlobleStr.MoveAiConf)

WriteConfigTable(worksheet, moveAIs);

else if (sheetName == GlobleStr.WeaponConf)

WriteConfigTable(worksheet, weapons);

else if (sheetName == GlobleStr.BulletConf)

WriteConfigTable(worksheet, bullets);

else if (sheetName == GlobleStr.SkillConf)

WriteConfigTable(worksheet, skills);
    }

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

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

return result.Tables[sheetName].Rows;
    }

static DataSet ReadExcel(string excelName)
    {
        string path = Application.dataPath + "/" + excelName;
        FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.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 collect, string fieldName)
    {
        // 标题名称
        var titles = collect[0];
        for (int j = 0; j < titles.ItemArray.Length; j++)
        {
            var title = titles[j];
            if(title.ToString() == fieldName)
            return j;
        }
        return -1;
    }

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

// 从Excel读配置数据(反射)
    public static List<T> ReadConfigTable<T>(string excelName, string sheetName) where T:CCObj,new()
    {
        List<T> list = new List<T>();

DataRowCollection collect = TryReadExcel(excelName, sheetName);
        if (collect.Count == 0) return null;

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

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

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

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

for (int j = 0; j < fields.Length;j++)
            {
                var fieldName = fields[j];
                int id = GetFieldId(collect, fieldName);
                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 excelName, string 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(worksheet, sheetName);

//保存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;

// 敌人引用
    [SerializeField] List<EnemyCtr> enmeyCtrs;
    // 子弹引用
    [SerializeField] List<BulletCtr> bulletCtrs;
    // 子弹引用
    [SerializeField] List<SkillCtr> skillCtrs;
    // 玩家引用
    [SerializeField] RoleCtr roleCtr;
    // 本波死亡敌人总数
    [SerializeField] int deathNum;

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

/** 玩家 (不需要移动ai,仅加载攻击ai)
     * 
     */
    private T CreateRoleCommon<T>(RoleConfig conf, Vector3 pos, Quaternion rot) where T : PlayerCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefab, pos, rot);

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

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

ctr.SetConfig(conf, weaponConf);
        ctr.SetWeaponAI(weaponAI);

ctr.IsEnemy = false;

return ctr;
    }

/** 敌人 (加载移动ai, 攻击ai)
     * 
     */
    private T CreateEnemyCommon<T>(RoleConfig conf, Vector3 pos, Quaternion rot) where T : PlayerCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefab, pos, rot);

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

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

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

ctr.SetConfig(conf, weaponConf);
        ctr.SetMoveAI(moveAI);
        ctr.SetWeaponAI(weaponAI);

ctr.IsEnemy = true;

return ctr;
    }

/** 创建子弹(加载移动ai)
     * 
     */
    private T CreateBulletCommon<T>(BulletConfig conf, Vector3 pos, Quaternion rot, bool isEnemy) where T : BulletCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefab, pos, rot);

// 添加移动ai
        var moveConf = battleConfs.GetConfById<MoveAIConfig>(conf.moveAiId, battleConfs.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 conf, Vector3 pos, Quaternion rot) where T : SkillCtrBase
    {
        // 加载模型
        var obj = UtilTool.CreateObjByName(conf.prefab, pos, rot);

// 添加移动ai
        var moveConf = battleConfs.GetConfById<MoveAIConfig>(conf.moveAiId, battleConfs.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 = 0; i < enmeyCtrs.Count; i++)
        {
            enmeyCtrs[i] = null;
        }
        enmeyCtrs.Clear();
    }

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

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

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

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

for (int i = 0; i < skillCtrs.Count; i++)
        {
            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 gConfs, GlobleLocalData gLocalData, BattleConfs 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 = 0; i < enmeyCtrs.Count;i++)
        {
            enmeyCtrs[i].OnUpdate(deltaTime);
        }

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

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

/** 创建角色
     * 
     */
    public RoleCtr CreateRole(string roleId, Vector3 pos, Quaternion rot)
    {
        var conf = battleConfs.GetConfById<RoleConfig>(roleId, battleConfs.GetRoleConfs()); //currLevelConf.playerId

var ctr = CreateRoleCommon<RoleCtr>(conf, pos, rot);
        ctr.OnStart();

roleCtr = ctr;
            
        return ctr;
    }

/** 创建敌人
     * 
     */
    public EnemyCtr CreateEnemy(string enemyId, Vector3 pos, Quaternion rot)
    {
        var conf = battleConfs.GetConfById<RoleConfig>(enemyId, battleConfs.GetRoleConfs());

var ctr = CreateEnemyCommon<EnemyCtr>(conf, pos, rot);
        ctr.OnStart();

enmeyCtrs.Add(ctr);

return ctr;
    }

/** 创建子弹
    * 
    *  isEnemy 是玩家还是敌人发射的
    */
    public BulletCtr CreateBullet(string bullectID, Vector3 pos, Quaternion rot, bool isEnemy)
    {
        var conf = battleConfs.GetConfById<BulletConfig>(bullectID, battleConfs.GetBulletConfs());

var ctr = CreateBulletCommon<BulletCtr>(conf, pos, rot, isEnemy);
        ctr.OnStart();

bulletCtrs.Add(ctr);

return ctr;
    }

/** 创建敌人
    * 
    */
    public SkillCtr CreateSkill(string skillId, Vector3 pos, Quaternion rot)
    {
        var conf = battleConfs.GetConfById<SkillConfig>(skillId, battleConfs.GetSkillConfs());

var ctr = CreateSkillCommon<SkillCtr>(conf, pos, rot);
        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.position, v.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.position, v.transform.position);
            if(tempDis > dis)
            {
                tempDis = dis;
                ctr = v;
            }
        }

return ctr;
    }

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

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

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

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

ctr.ReSetWeaponConfig(newWeaponConf, skillConf.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(0f, 0f, 10f));
        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 = { this, this.transform, this.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
{
    //内部属性
    //--------------------------------------------------------------------------
    [SerializeField] protected WeaponConfig tempWeaponConf;  // 武器配置(技能等意外获得武器)
    [SerializeField] protected float skillTime;              // 技能生效时间
    [SerializeField] protected float skillDelta;             //
    [SerializeField] protected bool skilling = false;        // 技能生效中

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

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

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

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

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

/** 技能生效
     * 
     */
    public virtual void OnSkillStart()
    {
        object[] args = { this, this.transform, this.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 == null) return;
        if (this.conf == null) return;
        if (isStart == false) return;

// 碰撞检测
        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 wc, float time)
    {
        this.tempWeaponConf = wc;
        this.skillTime = time;
        this.skillDelta = 0f;

this.OnSkillStart();
    }

/** 初始化 config 和 data(血量最大值等)
     * 
     */
    public void SetConfig(RoleConfig c, WeaponConfig 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;
    }

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

/** 死亡标记
     * 
     */
    [SerializeField] protected 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.position, transform.position);
        if (inScope)
        {
            Debug.LogError("玩家获得技能 " + player.gameObject.name);

battle.battleDatas.SwitchToSkill(player, this.skillConf);


    }

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

this.moveAI.OnStart(args);

base.OnStart();
    }

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

}

(五) 武器切换(使用技能)相关推荐

  1. 计算机培训教学准备,计算机教学计划锦集五篇

    计算机教学计划锦集五篇 时间的脚步是无声的,它在不经意间流逝,我们的工作同时也在不断更新迭代中,写一份计划,为接下来的工作做准备吧!好的计划是什么样的呢?以下是小编为大家整理的计算机教学计划5篇,仅供 ...

  2. 第五人格调香师技能可以用几次?

    第五人格新晋求生者调香师技能很有趣,可以移行换位,乍一看感觉是个溜鬼小能手,但是第五人格调香师技能可以用几次?这个问题就很关键了,就像魔术师的魔术棒,虽然很好用,但却只有两次使用机会,让人意犹未尽,调 ...

  3. 第五人格第十赛季服务器维护,第五人格第十赛季正式开启 12月5日更新内容

    第五人格第十赛季正式开启.在今天更新后,很多新内容将上线,其中包括第十赛季精华一的皮肤以及新求生者邮差,当然小伙伴们所关心的深渊的呼唤3也即将开始报名,那么小伙伴们想知道本周的更新内容吗?一起来看看吧 ...

  4. 五年级计算机课主要学哪些,小学五年级信息技术教学设计

    小学五年级信息技术教学设计 一. 教材分析 教学内容: 五年级上册教材共分三个单元:多媒体素材的采集与处理.有声有色话家乡(Powerpoint).建设网上家园(Frontpage).根据课时安排.综 ...

  5. 第五人格周四服务器维护中,第五人格新监管者疯眼上线 将于每周四早上8:30进行停服维护...

    :原标题:第五人格新监管者疯眼上线 将于每周四早上8:30进行停服维护 第五人格11月15日更新内容有哪些?今天游戏更新之后将上线一位新的监管者疯眼,疯眼可以在第四赛季精华2中进行解锁,下面就来一起详 ...

  6. 计算机组装与维护教学工作计划,计算机教学计划范文五篇

    计算机教学计划范文五篇 时间的脚步是无声的,它在不经意间流逝,我们又将接触新的知识,学习新的技能,积累新的经验,是时候抽出时间写写计划了.那么计划怎么拟定才能发挥它最大的作用呢?下面是小编为大家整理的 ...

  7. 第五人格问题服务器维护中,第五人格5月30日停服维护-更新内容一览-安致网

    第五人格5月30日要停服维护?为保证庄园的稳定运行,第五人格将进行停服维护,同时进行更新与问题修复,下面随着安致网小编来看看第五人格5月30日停服维护更新内容,感兴趣的小伙伴们赶紧前来围观吧! 5月3 ...

  8. 第五人格8月8日服务器维护几小时,第五人格6月8日无法登陆是怎么回事

    网易第五人格官方微博出了临时公告:目前登陆服务器出现了一些问题,导致玩家暂时无法登陆,我们已经在紧急修复当中,请大家稍安勿躁,在游戏内的玩家目前暂无影响. [2018年6月7日版本]更新内容 商城 [ ...

  9. 第五人格服务器6月维护,第五人格6月7日更新维护公告 更新内容汇总

    第五人格 6 月 7 日迎来了更新,求生者-祭司正式开放,下面我们来看下今天的更新具体有哪些内容吧. [ 2018 年 6 月 7 日版本]更新内容: 商城: --[角色]:求生者-祭司正式开放,可以 ...

最新文章

  1. n个素数构成等差数列
  2. c++语言中,vector容器与list容器的区别和联系?_百度知道
  3. 制药行业SAP项目里的那些LIMS系统
  4. SQL DBHelp.cs 操作数据库的底层类
  5. 数据库之存储引擎,数据类型-30
  6. 安卓开发中RelativeLayout中的各个属性
  7. Android 省,市,区选择权
  8. 我的一个学生在运维工作中写的自动日志清理脚本程序
  9. 惊人体积,无码改造,黑月V1.7.4增强版[20110810]
  10. C/C++ 函数指针调用函数
  11. 迎新年\年会背景PSD分层模板
  12. Python图片爬虫
  13. WPF/Silverlight深度解决方案:(四)基于像素的图像合成(For WPF)
  14. 2022年前端面试宝典【1万字带答案】
  15. 通讯录管理系统JAVA版本
  16. Pandas库的基本使用方法
  17. 先验 超验_经验、先验、超验
  18. 项目jar包启动的命令
  19. ios13 微信提示音插件_iOS13免越狱修改微信提示音方法!亲测有用!
  20. 虚拟化介绍及Docker与传统虚拟化有什么区别

热门文章

  1. dota2起源1和2引擎区别_DOTA2正式启用起源2引擎 “强制”使用或引玩家反感
  2. 堆树(最大堆、最小堆)详解
  3. 好文荐读 | 2019,沉默的链游
  4. 值得推荐的几个图片素材网站!!!用过记得收藏
  5. vivo恢复出厂设置后云服务器,vivo 手机恢复出厂设置后不能开机,怎么办,一招就可解决!...
  6. excel计算机二级函数,计算机二级的excel函数
  7. 小米路由器3四根天线 99%的人都摆错了
  8. Pygame游戏入门极简思维导图
  9. bbcp linux,使用BBCP来提高跨网数据传输速度
  10. 226. 翻转二叉树【58】