Files
XMen/Assets/Scripts/GameManager.cs

1560 lines
47 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using BestHTTP;
using BestHTTP.JSON;
using DragonLi.Core;
using JetBrains.Annotations;
using MechanicalAge;
using Mirror;
using Unity.Mathematics;
using Unity.VisualScripting;
using Unity.XR.PXR;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.Interaction.Toolkit;
using XPlugin.Data.Json;
using XPlugin.Data.JsonLiteDB;
using static XPlugin.Data.JsonLiteDB.JsonLiteDB;
using Random = UnityEngine.Random;
/// <summary>
/// 游戏场地
/// </summary>
public enum GamePlace
{
Company1Floor=0,
LiaoningAnShan=1,
HangZhouLongHuTianJie=2,
Nanjing_Yuhua_Wanxiang=3,
Nanjing_Xianlin_WanDaMao=4,
Yangzhou_Hanjiang_Tansuozhongxin=5,
Yangzhou_Hanjiang_TansuoZhongxin_wai=-5,
Zhejiang_Jinhua_KeJiGuan = 6,
Anhui_Wuhu_Guanwei = 8,
Shandong_Jining_Wanhuicheng_nei =-9,
Shandong_Langfang_QingzhouTaihuacheng=10,
Hubei_Xiangyang_Kejiguan=11,
Zhejiang_Shaoxing_Shengzhou_WuyueGuangchang=12,
Hunan_Jishou_Qianzhou_Tianhong=13,
Jilin_Tonghua_Liuhe=14,
Shandong_Jinan_Huaiyin_ShengfutongShangmao=15,
Shandong_Jinan_Huaiyin_ShengfutongShangmao_wai=-15,
Henan_Xinzheng_Shuanghudadao_Longhujinyicheng = 16,
}
public class GameManager : NetworkBehaviour
{
public static GameManager Ins { get; private set; }
private string Version = "2.1.9";
//private string Author = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiJhMGE4OTE0ZjRjODE0NTNiYWZmMTdiODFmYjBjNmU5YSIsInVzZXIiOiJkZXZpY2UtMDAxIiwic3ViIjoiZGV2aWNlLTAwMSJ9.krKxq1NQYUTlqAMcb0FwHlsI17TLos08OjqUIi_5zmK8sh-LA6hL2awyXZpblrE-LYuWh0g8qA8DjRcjP74hOQ";
private string Author = "";
public string HttpServerUrl = "";
[SyncVar]
public List<Transform> players;
//[NonSerialized]
[SyncVar]
public List<Transform> enemyList = new List<Transform>();
/// <summary>
/// 护盾
/// </summary>
private Dictionary<int, Shield> Shields = new Dictionary<int, Shield>();
private int ShieldId = 0;
[SyncVar]
public int AllEnemyAmount;
/// <summary>
/// 在倒计时之内
/// </summary>
[SyncVar]
public bool isWithinTime = true;
[SyncVar]
// 游玩结束时间
public long vistEnd = 0;
//总共游玩时间
// 总游玩时长
private int vistAllTime = (int)(60 * 10f);
// json数据库
private JsonLiteDB DB;
// 怪物详情
public Dictionary<int, EnemyInfo> EnemyDescInfos = new Dictionary<int, EnemyInfo>();
// 武器详情
public Dictionary<int, WeaponData> WeaponDescInfos = new Dictionary<int, WeaponData>();
// 道具表
public Dictionary<int, PropInfo> PropDescInfos = new Dictionary<int, PropInfo>();
// 关卡难度
public Dictionary<int, DifficultyInfo> DifficultyescInfos = new Dictionary<int, DifficultyInfo>();
// 称号表
public Dictionary<int, TitleInfo> TitleDescInfos = new Dictionary<int, TitleInfo>();
// 子弹详情
public Dictionary<int, BulletInfo> BulletDescInfos = new Dictionary<int, BulletInfo>();
//剧情
public Dictionary<int, StoryInfo> StoryDescInfos = new Dictionary<int, StoryInfo>();
public Dictionary<int, TitleConditionInfo> titleConditionDescInfos = new Dictionary<int, TitleConditionInfo>();
public Dictionary<int, StoryInfo1> GameStoryInfos = new Dictionary<int, StoryInfo1>();
//临时对象
public Dictionary<int, TempInfo> tempDescInfos = new Dictionary<int, TempInfo>();
// 保存传送门
public List<GameObject> cracksList = new List<GameObject>();
[Header("预制体")]
public GameObject wallPre;
public GameObject doorPre;
public GameObject EnergyPumpPre;
public GameObject gameStartPointPre;
[Header("怪物预制体")]
public GameObject RobotGuardianPre;
public GameObject CrackPre;
public GameObject QYPre;
public GameObject EskyPre;
public GameObject TurretPre;
public GameObject SpiderPre;
public GameObject EliteSpiderPre;
public GameObject RobotMechPre;
public GameObject EskyClonePre;
public GameObject SpiderClonePre;
public GameObject ShadowPre;
public GameObject ShadowCastPre;
public GameObject BossPre;
public GameObject MachineHeartPre;
public GameObject HudPre;
public GameObject radarPoint;
//闪电特效
public GameObject LightningPre;
/// <summary>
/// 护盾
/// </summary>
public GameObject ShieldPre;
/// <summary>
/// 血包
/// </summary>
public GameObject BloodBagPre;
/// <summary>
/// 武器道具
/// </summary>
public GameObject WeaponPropPre;
/// <summary>
/// 攻击BUFF
/// </summary>
public GameObject AtkBuffPre;
public GameObject deffBuffPre;
[Header("特效")]
public GameObject RockfallPre;
public GameObject BOSS_lightPre;
//激光蓄力
public AudioClip xuliEffect;
//激光射线
public AudioClip LayEffect;
//切换枪支
public AudioClip SwitchGunEffect;
public Collider StartPoint;
public GameObject Landmarks;
[SyncVar]
public bool GameStart = false;
//怪物index
[NonSerialized]
[SyncVar]
public int EnemyAmount = 0;
[SyncVar]
public int SummonAmount = 0;
[NonSerialized]
[SyncVar]
public float PumpsMaxAmount = 5;
public ScriptableObject scriptMachineGraph;
private Shadow NowShadow;
[SyncVar]
public bool isGameEnd = false;
[SyncVar]
public int EnergyPumpTag = 0;
[SyncVar]
public float EnergyPumpFillAmount = 0;
public float buffAtk = 0f;
public float buffDef = 0f;
public AuthInfo authInfo=new AuthInfo();
//关闭手柄射线
[ClientRpc]
public void CloseLay()
{
GameInit.Ins.MRLeftControl.GetComponent<XRRayInteractor>().enabled = false;
GameInit.Ins.MRRightControl.GetComponent<XRRayInteractor>().enabled = false;
}
private void Awake()
{
AllEnemyAmount = -1;
}
public void Start()
{
Ins = this;
Landmarks = GameInit.Ins.Landmarks;
vistEnd = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds + vistAllTime;
if (isClient)
{
// 鉴权
AuthorPanel.Show();
}
#if !UNITY_EDITOR
// PXR_Enterprise.InitEnterpriseService();
// PXR_Enterprise.BindEnterpriseService();
#endif
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
CustomEvent.Trigger(GameInit.Ins.Event.gameObject, "GameManager", transform);
if (isClient)
{
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
// 创建头盔
CustomEvent.Trigger(GameInit.Ins.Event.gameObject, "StartGame");
GenerateHUD();
}, 0.5f);
}
}, 1.0f);
}
public void Update()
{
// if (isServer && enemyList.Count > 0)
// {
// List<Vector3> vectors = new List<Vector3>();
// for (int i = 0; i < enemyList.Count; i++)
// {
// if (enemyList[i] != null)
// {
// vectors.Add(enemyList[i].position);
// }
// }
// EnemysPosRpc(vectors);
// }
}
/// <summary>
/// 鉴权
/// </summary>
public void RequestAuth(Action<HTTPRequest, HTTPResponse> cb = null)
{
string url = "http://www.pineappletech.cn/startcount";
HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Post, (req, response) =>
{
if (response != null)
{
Debug.Log("收到数据 ->" + response.DataAsText);
}
cb?.Invoke(req, response);
});
//request.AddHeader("Authorization", Author);
authInfo.deviceSn = GetSn();
authInfo.startAt = ConvertTimestampToDateTime(GetTimestamp()) + "";
//authInfo.paid = 2;
//authInfo.uuid = GetSn() + GetTimestamp();
authInfo.shop = 0;
#if !UNITY_EDITOR && UNITY_ANDROID && PICO
authInfo.shop = (int)GameInit.Ins.gamePlace;
if(GameInit.Ins.gamePlace== GamePlace.Yangzhou_Hanjiang_TansuoZhongxin_wai)
authInfo.shop = 5;
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Jining_Wanhuicheng_nei)
authInfo.shop = 9;
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Jinan_Huaiyin_ShengfutongShangmao_wai)
authInfo.shop = 15;
#endif
//authInfo.shop = 0;
authInfo.gameId = 2;
string authJson = JsonUtility.ToJson(authInfo);
Debug.Log("发送数据 -> " + authJson);
request.RawData = System.Text.Encoding.UTF8.GetBytes(authJson);
request.AddHeader("Content-Type", "application/json");
request.Send();
}
[ClientRpc]
public void GameEnd()
{
//RequestNotifyEnd();
}
/// <summary>
/// 通知服务器已开始游戏
/// </summary>
// public void RequestNotifyStart(Action cb = null)
// {
// string url = HttpServerUrl + "/api/record";
// HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Put, (req, response) =>
// {
// if (response != null)
// {
// Debug.Log("收到数据 ->" + response.DataAsText);
// cb?.Invoke();
// }
// });
// request.AddHeader("Authorization", Author);
// authInfo.paid = 1;
// string authJson = JsonUtility.ToJson(authInfo);
// Debug.Log("发送数据 -> " + authJson);
// request.RawData = System.Text.Encoding.UTF8.GetBytes(authJson);
// request.AddHeader("Content-Type", "application/json");
// request.Send();
// }
/// <summary>
/// 通知服务器游戏结束
/// </summary>
public void RequestNotifyEnd(Action<HTTPRequest, HTTPResponse> cb = null)
{
// string url = HttpServerUrl + "/api/record";
// HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Put, (req, response) =>
// {
// if (response != null)
// {
// Debug.Log("收到数据 ->" + response.DataAsText);
// cb?.Invoke(req, response);
// }
// });
// request.AddHeader("Authorization", Author);
// authInfo.endAt = ConvertTimestampToDateTime(GetTimestamp()) + "";
// authInfo.dur = (int)(((long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds) - (vistEnd - vistAllTime));
// Debug.Log("dur---:" + authInfo.dur);
// string authJson = JsonUtility.ToJson(authInfo);
// Debug.Log("发送数据 -> " + authJson);
// request.RawData = System.Text.Encoding.UTF8.GetBytes(authJson);
// request.AddHeader("Content-Type", "application/json");
// request.Send();
}
/// <summary>
/// 游戏开始
/// </summary>
/// <summary>
/// 请求配置
/// </summary>
public void RequestConf(Action<HTTPRequest, HTTPResponse> cb = null)
{
string url = HttpServerUrl + "/api/config/info?deviceSn={0}&gameType=1&version={1}";
url = string.Format(url, GetSn(), Version);
Debug.Log("发送数据 -> " + url);
HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, response) =>
{
cb?.Invoke(req, response);
});
request.AddHeader("Authorization", Author);
request.Send();
}
/// <summary>
/// 更新配置表
/// </summary>
public void UpdateConf()
{
string text = "";
string text0 = Resources.Load<TextAsset>(string.Format("zh/{0}Data",GameInit.Ins.gamePlace)).text;
ParseGameJson(text0);
// switch (gamePlace)
// {
// case GamePlace.HongYueCheng:
// RequestConf((req, response) =>
// {
// if (response != null)
// {
// Debug.Log("收到数据 -> " + response.DataAsText);
// JObject jObj = JObject.OptParse(response.DataAsText);
// text = jObj["data"]["data"].AsString();
// int status = jObj["status"].AsInt();
// if (status >= 200 && status < 300 && text != "")
// {
// ParseGameJson(text);
// }
// else
// {
// string text0 = Resources.Load<TextAsset>("MechanicalAgeDataHongYuecheng").text;
// ParseGameJson(text0);
// }
// }
// else
// {
//
// string text0 = Resources.Load<TextAsset>("MechanicalAgeDataHongYuecheng").text;
// ParseGameJson(text0);
// }
// });
// break;
// case GamePlace.BeiJing:
// text = Resources.Load<TextAsset>("MechanicalAgeDataBeiJing").text;
// ParseGameJson(text);
// break;
// case GamePlace.YuHua:
// text = Resources.Load<TextAsset>("MechanicalAgeDataYuHua").text;
// ParseGameJson(text);
// break;
// case GamePlace.ZhengHong:
// text = Resources.Load<TextAsset>("MechanicalAgeDataZhengHong").text;
// ParseGameJson(text);
// break;
// case GamePlace.SuZhouAoti:
// text = Resources.Load<TextAsset>("MechanicalAgeDataAoti").text;
// ParseGameJson(text);
// break;
// case GamePlace.JNWD_F2:
// text = Resources.Load<TextAsset>("JNWD").text;
// ParseGameJson(text);
// break;
// case GamePlace.JNWD_F1:
// text = Resources.Load<TextAsset>("JNWD_F1").text;
// ParseGameJson(text);
// break;
//
// }
}
public static string ConvertTimestampToDateTime(long timestamp)
{
// Unix时间戳是从1970年1月1日00:00:00开始的秒数或毫秒数
// 这里以秒为单位如果时间戳是毫秒则除以1000
DateTime dateTime = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;
return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 解析游戏使用的json
/// </summary>
public void ParseGameJson(string text)
{
DB = new JsonLiteDB();
DB.Load(text);
// 读取Info表数据
TableReader infoReader = DB["EnemyInfo"].GetReader();
Dictionary<int, EnemyInfo> EnemyDescInfosC = new Dictionary<int, EnemyInfo>();
while (infoReader.Read())
{
EnemyInfo info = new EnemyInfo(infoReader);
EnemyDescInfosC.Add(info.Id, info);
}
EnemyDescInfos = EnemyDescInfosC;
// 读取武器表数据
TableReader weaponReader = DB["WeaponInfo"].GetReader();
Dictionary<int, WeaponData> WeaponDescInfosC = new Dictionary<int, WeaponData>();
while (weaponReader.Read())
{
WeaponData info = new WeaponData(weaponReader);
WeaponDescInfosC.Add(info.Id, info);
}
WeaponDescInfos = WeaponDescInfosC;
// 解析子弹详情表
TableReader BulletReader = DB["BulletInfo"].GetReader();
Dictionary<int, BulletInfo> BulletDescInfosC = new Dictionary<int, BulletInfo>();
while (BulletReader.Read())
{
BulletInfo info = new BulletInfo(BulletReader);
BulletDescInfosC.Add(info.ID, info);
}
BulletDescInfos = BulletDescInfosC;
// 道具表
TableReader PropReader = DB["PropInfo"].GetReader();
Dictionary<int, PropInfo> PropDescInfosC = new Dictionary<int, PropInfo>();
while (PropReader.Read())
{
PropInfo info = new PropInfo(PropReader);
PropDescInfosC.Add(info.PropId, info);
}
PropDescInfos = PropDescInfosC;
// 关卡难度表
TableReader DifficultyReader = DB["DifficultyInfo"].GetReader();
Dictionary<int, DifficultyInfo> DifficultyescInfosC = new Dictionary<int, DifficultyInfo>();
while (DifficultyReader.Read())
{
DifficultyInfo info = new DifficultyInfo(DifficultyReader);
DifficultyescInfosC.Add(info.Id, info);
}
DifficultyescInfos = DifficultyescInfosC;
// 称号列表
TableReader TitleDescInfosReader = DB["TitleInfo"].GetReader();
Dictionary<int, TitleInfo> TitleDescInfosC = new Dictionary<int, TitleInfo>();
while (TitleDescInfosReader.Read())
{
TitleInfo info = new TitleInfo(TitleDescInfosReader);
TitleDescInfosC.Add(info.Id, info);
}
TitleDescInfos = TitleDescInfosC;
TableReader storyReader = DB["Story"].GetReader();
while (storyReader.Read())
{
StoryInfo info = new StoryInfo(storyReader);
StoryDescInfos.Add(info.Id, info);
}
TableReader titleConditionInfo = DB["TitleConditionInfo"].GetReader();
while (titleConditionInfo.Read())
{
TitleConditionInfo info = new TitleConditionInfo(titleConditionInfo);
titleConditionDescInfos.Add(info.Id, info);
}
TableReader tempReader = DB["TempInfo"].GetReader();
while (tempReader.Read())
{
TempInfo info = new TempInfo(tempReader);
tempDescInfos.Add(info.Id, info);
}
}
/// <summary>
/// 获取sn号
/// </summary>
public string GetSn()
{
string res = "UnityEditor";
// string res = "PA8E10MGH7210380D";
#if !UNITY_EDITOR && UNITY_ANDROID && PICO
res = PXR_Enterprise.StateGetDeviceInfo(SystemInfoEnum.EQUIPMENT_SN);
#endif
return res;
}
public long GetTimestamp()
{
return (long)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
[ClientRpc]
public void EnemysPosRpc(List<Vector3> vectors)
{
EventDispatcher.TriggerEvent("EnemyList", vectors);
}
[ClientRpc]
public void ShowWinUI(float time)
{
if (GameInit.Ins.Win)
GameInit.Ins.Win.SetActive(true);
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
GameInit.Ins.Win.SetActive(false);
}, time);
}
public void PlaySwitchGunSound()
{
GameInit.Ins.bgm.PlayOneShot(SwitchGunEffect);
}
[ClientRpc]
public void ShowJxsdLogo()
{
GameInit.Ins.JxsdLogo.SetActive(true);
}
[ClientRpc]
public void PlayOneShotAudioTrriger(string name)
{
EventDispatcher.TriggerEvent("PlayOnShotAudio", "Audio/" + name);
//
//CustomEvent.Trigger(GameInit.Ins.Event.gameObject, "PlayOnShotAudio");
}
public void PlayAudioTrriger(string name)
{
EventDispatcher.TriggerEvent("PlayAudio", "Audio/Background" + name);
}
//---------------播放音乐-------------------
[ClientRpc]
public void PlayXuliSound()
{
GameInit.Ins.bgm.PlayOneShot(xuliEffect);
}
[ClientRpc]
public void StopSound()
{
GameInit.Ins.bgm.Stop();
}
// 游戏开始
[Server]
public void GameOK()
{
GameStart = true;
//关闭射线
CloseLay();
StartPointClose();
}
public string FormatTime(int totalSeconds)
{
int hours = totalSeconds / 3600;
// string hh = hours < 10 ? "0" + hours : hours.ToString();
int minutes = (totalSeconds - hours * 3600) / 60;
string mm = minutes < 10f ? "0" + minutes : minutes.ToString();
int seconds = totalSeconds - hours * 3600 - minutes * 60;
string ss = seconds < 10 ? "0" + seconds : seconds.ToString();
return string.Format("{0}:{1}", mm, ss);
}
public GameObject GenerateHUD()
{
OverlayUIManager.Ins.Cover("UI/HUD", false);
//return Instantiate(HudPre, new Vector3(2000, 0, 0), quaternion.identity);
return null;
}
[ClientRpc]
public void ShowLandmark(int index1, int index2)
{
return;
GameObject landmark1 = Landmarks.transform.GetChild(index1).gameObject;
GameObject landmark2 = Landmarks.transform.GetChild(index2).gameObject;
if (index2 == 0)
{
landmark1.SetActive(true);
}
else
{
landmark1.SetActive(false);
landmark2.SetActive(true);
}
}
[ClientRpc]
public void StartPointClose()
{
if (StartPoint)
{
StartPoint.gameObject.SetActive(false);
}
}
public void CreateItemDrop(int enemyIndex, Vector3 pos)
{
int storyId = StoryManager.Ins.currentStoryIndex - 1;
StoryInfo storyInfo = StoryDescInfos[storyId];
//当前怪物的序号 索引从开始需要加1
int currentIndex = (enemyIndex + 1);
if (currentIndex % storyInfo.ItemRule == 0)
{
if (storyInfo.ALLEnemyAmount[StoryManager.Ins.gameDifficulty] > 1)
{
int counter = Mathf.FloorToInt(currentIndex / storyInfo.ItemRule);
int itemIndex = (counter - 1) % storyInfo.ItemDrop.Length; // 使用取余操作符确保循环索引
Debug.Log($"当前怪物index:{enemyIndex}当前物品index:{itemIndex}当前物品ID:{storyInfo.ItemDrop[itemIndex]}");
if (storyInfo.BulletAmount.ContainsKey(storyInfo.ItemDrop[itemIndex]))
{
int amount = storyInfo.BulletAmount[storyInfo.ItemDrop[itemIndex]];
Debug.Log("amount" + amount);
CreateItemProp(storyInfo.ItemDrop[itemIndex], pos, amount);
}
else
{
CreateItemProp(storyInfo.ItemDrop[itemIndex], pos);
}
}
else
{
for (int i = 0; i < storyInfo.ItemDrop.Length; i++)
{
int key = storyInfo.ItemDrop[i];
if (storyInfo.BulletAmount.ContainsKey(key))
{
int amount = storyInfo.BulletAmount[key];
CreateItemProp(storyInfo.ItemDrop[i], pos + new Vector3(i + 0.5f, 0, 0), amount);
// Debug.Log("当前子弹数量为:" + amount);
}
else
{
CreateItemProp(storyInfo.ItemDrop[i], pos + new Vector3(i + 0.5f, 0, 0));
}
}
}
}
}
// // 解锁所有人的超级武器
// [Server]
// public void UnLockAllSuperGunServer()
// {
// Debug.Log("解锁所有人的超级武器");
// UnLockSuperGun();
// }
// [Server]
// public void DestoryALLWeapon()
// {
// SwitchNULL();
// }
// [ClientRpc]
// public void SwitchNULL()
// {
// GameInit.Ins.self.SwitchNULL();
// }
// [ClientRpc]
// public void UnLockSuperGun()
// {
// GameInit.Ins.self.UnLockSuperGun();
// }
// 给所有客户端播放音乐
[ClientRpc]
public void PlayeBGM2AllClient()
{
CustomEvent.Trigger(GameInit.Ins.Event.gameObject, "PlayBGM2");
}
[ClientRpc]
public void PlayerBGM()
{
CustomEvent.Trigger(GameInit.Ins.Event.gameObject, "PlayBGM2");
}
public void WaitDestoryObject(GameObject obj, float time)
{
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
NetworkServer.Destroy(obj);
}, time);
}
void Destroy()
{
#if !UNITY_EDITOR
//PXR_Enterprise.UnBindEnterpriseService();
#endif
}
[Server]
public void InitEnemyAmount()
{
EnemyAmount = 0;
enemyList.Clear();
}
public Transform RandomFloundEnemy(XAgent.BodyPoint point)
{
List<Transform> notNullElements = enemyList.Where(element => element != null).ToList();
Transform res = null;
if (notNullElements.Count > 0)
{
Transform enemy = notNullElements[Random.Range(0, notNullElements.Count)];
if (enemy != null)
{
res = enemy.GetComponent<XAgent>().FindBody(point);
}
}
return res;
}
public List<Transform> GetRangeEnemys(Vector3 Pos, float radius)
{
Collider[] colliders;
colliders = new Collider[15];
int colliderCount = Physics.OverlapSphereNonAlloc(Pos, radius, colliders);
List<Transform> enemys = new List<Transform>();
for (int i = 0; i < colliderCount; i++)
{
if (colliders[i].CompareTag("Enemy"))
{
enemys.Add(colliders[i].transform);
}
}
return enemys;
}
public List<Transform> GetRangePlayers(Vector3 Pos, float radius)
{
Collider[] colliders;
colliders = new Collider[15];
int colliderCount = Physics.OverlapSphereNonAlloc(Pos, radius, colliders);
List<Transform> players = new List<Transform>();
for (int i = 0; i < colliderCount; i++)
{
if (colliders[i].CompareTag("Player"))
{
players.Add(colliders[i].transform);
}
}
return players;
}
public Transform[] FoundNearestEnemy(int amount, Transform self)
{
if (enemyList.Count <= 0) return null;
var sortedEnemies = enemyList.OrderBy(e => Vector3.Distance(self.position, e.position));
if (enemyList.Count >= amount)
{
return sortedEnemies.Take(amount).ToArray();
}
else
{
return sortedEnemies.Take(enemyList.Count).ToArray();
}
}
//创建能量泵
[Server]
public void GenerateEnergyPump(Vector3 pos)
{
GameObject EnergyPump = Instantiate(EnergyPumpPre);
NetworkServer.Spawn(EnergyPump);
//EnergyPump.transform.position = pos;
EnergyPump.transform.position = pos;
if(GameInit.Ins.gamePlace == GamePlace.Company1Floor)
{
EnergyPump.transform.position = new Vector3(-3f, 0, 5f);
}
if(GameInit.Ins.gamePlace == GamePlace.Zhejiang_Jinhua_KeJiGuan)
{
EnergyPump.transform.position = new Vector3(-3f, 0, 5f);
}
if(GameInit.Ins.gamePlace == GamePlace.Anhui_Wuhu_Guanwei)
{
EnergyPump.transform.position = new Vector3(-1.6f, 0, 1.6f);
}
if(GameInit.Ins.gamePlace == GamePlace.Zhejiang_Shaoxing_Shengzhou_WuyueGuangchang)
{
EnergyPump.transform.position = new Vector3(-3f, 0, 5f);
}
if (GameInit.Ins.gamePlace == GamePlace.Nanjing_Xianlin_WanDaMao)
{
EnergyPump.transform.position = new Vector3(-1.2f,0,1.5f);
}
if (GameInit.Ins.gamePlace == GamePlace.Yangzhou_Hanjiang_Tansuozhongxin)
{
EnergyPump.transform.position = new Vector3(1,0,-2.61f);
}
if (GameInit.Ins.gamePlace == GamePlace.Yangzhou_Hanjiang_TansuoZhongxin_wai)
{
EnergyPump.transform.position = new Vector3(0,0,2f);
}
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Jining_Wanhuicheng_nei)
{
EnergyPump.transform.position = new Vector3(0,0,2f);
}
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Langfang_QingzhouTaihuacheng)
{
EnergyPump.transform.position = new Vector3(7.36f, 0, 7.58f);
}
if (GameInit.Ins.gamePlace == GamePlace.Hubei_Xiangyang_Kejiguan)
{
EnergyPump.transform.position = new Vector3(0,0,5f);
}
if (GameInit.Ins.gamePlace == GamePlace.Jilin_Tonghua_Liuhe)
{
EnergyPump.transform.position = new Vector3(1.87f,0,2.17f);
}
if (GameInit.Ins.gamePlace == GamePlace.Hunan_Jishou_Qianzhou_Tianhong)
{
EnergyPump.transform.position = new Vector3(0f,0,2f);
}
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Jinan_Huaiyin_ShengfutongShangmao)
{
EnergyPump.transform.position = new Vector3(-0.84f,0,-0.11f);
}
if (GameInit.Ins.gamePlace == GamePlace.Shandong_Jinan_Huaiyin_ShengfutongShangmao_wai)
{
EnergyPump.transform.position = new Vector3(0.09f,0,1.09f);
}
if (GameInit.Ins.gamePlace == GamePlace.Henan_Xinzheng_Shuanghudadao_Longhujinyicheng)
{
EnergyPump.transform.position = new Vector3(-1.6f,0,4.35f);
}
EnergyPumpTag++;
EnergyPump.GetComponent<EnergyPump>().Init(EnergyPumpTag);
}
//创建闪电
[Server]
public void GenerateLightning(Vector3 transform, Vector3 angle, float time)
{
GameObject Lightning = Instantiate(LightningPre);
NetworkServer.Spawn(Lightning);
Lightning.transform.position = transform;
Lightning.transform.eulerAngles = angle;
CoroutineTaskManager.Instance.WaitSecondTodo(() =>
{
NetworkServer.Destroy(Lightning);
}, time);
}
[ClientRpc]
public void ShowTex()
{
GameInit.Ins.Tex.SetActive(true);
}
[ClientRpc]
public void OpenCoillder(GameObject obj)
{
obj.GetComponent<CapsuleCollider>().enabled = true;
}
[Server]
public void DestoryEnergyPump(GameObject obj)
{
NetworkServer.Destroy(obj);
}
[Server]
public void GenerateWall(int index, Vector3 position, Vector3 angle)
{
//EnergyPump1
GameObject wall = Instantiate(wallPre);
//NetworkServer.Spawn(wall);
wall.tag = "Story" + index.ToString();
wall.transform.position = position;
wall.transform.eulerAngles = angle;
}
//创建雷达点
[Server]
public void GenerateRadarPoint()
{
GameObject point = Instantiate(doorPre);
NetworkServer.Spawn(point);
point.transform.position = new Vector3(transform.transform.position.x, transform.transform.position.y, transform.transform.position.z);
point.transform.localEulerAngles = new Vector3(0, 0, 0);
}
//创建大门
[Server]
public GameObject GenerateDoor()
{
GameObject door = Instantiate(doorPre);
Vector3 pos = tempDescInfos[1].Positions[0];
Vector3 scale = tempDescInfos[1].Scales[0];
NetworkServer.Spawn(door);
door.transform.position = new Vector3(pos.x, pos.y, pos.z);
door.transform.localScale = scale;
door.transform.localEulerAngles = tempDescInfos[1].Angles[0];
door.GetComponentInChildren<Animator>().SetBool("IsOpen", true);
return door;
}
// 创建巡逻兵
[Server]
public void GenerateRobotGuardian(Transform pos)
{
Debug.Log("创建巡逻兵");
GameObject RobotGuardian = Instantiate(RobotGuardianPre);
NetworkServer.Spawn(RobotGuardian);
RobotGuardian.transform.position = new Vector3(pos.transform.position.x, pos.transform.position.y, pos.transform.position.z);
RobotGuardian.GetComponent<RobotGuardian>().OnSpawn();
}
[Server]
public GameObject GenerateEnemy(EnemyType Type, Vector3 pos, Vector3 angle, Vector3 scale, string pathId = "0")
{
GameObject enemy = null;
switch (Type)
{
case EnemyType.RobotGuardian:
enemy = CreateRobotGuardian(pos, angle, scale, pathId);
break;
case EnemyType.QY:
enemy = CreateQY(pos, angle, scale, pathId);
break;
case EnemyType.Esky:
enemy = CreateEsky(pos, angle, scale, pathId);
break;
case EnemyType.Spider:
enemy = CreateSpider(pos, angle, scale, pathId);
break;
case EnemyType.EliteSpider:
enemy = CreateEliteSpiderPre(pos, angle, scale);
break;
case EnemyType.RobotMech:
enemy = CreateRobotMesh(pos, angle, scale);
break;
case EnemyType.Shadow:
enemy = CreateShadow(pos, angle, scale);
break;
case EnemyType.ShadowCast:
enemy = CreateShadowCast(pos, angle, scale);
break;
case EnemyType.Boss:
enemy = CreateBoos(pos, angle, scale, pathId);
break;
}
XAgent xagent = enemy.GetComponent<XAgent>();
xagent.index = EnemyAmount;
enemyList.Add(xagent.transform);
EnemyAmount++;
return enemy;
}
[Server]
public GameObject CreateQY(Vector3 pos, Vector3 angle, Vector3 scale, string pathId)
{
GameObject QY = Instantiate(QYPre);
NetworkServer.Spawn(QY);
QY.transform.position = pos;
QY.transform.localEulerAngles = angle;
QY.transform.localScale = scale;
QY qyScript = QY.GetComponent<QY>();
qyScript.OnSpawn();
qyScript.SetPathId(pathId);
return QY;
}
// 创建起义兵
[Server]
public GameObject CreateRobotGuardian(Vector3 pos, Vector3 angle, Vector3 scale, string pathId)
{
GameObject robotGuardian = Instantiate(RobotGuardianPre);
NetworkServer.Spawn(robotGuardian);
robotGuardian.transform.position = pos;
robotGuardian.transform.localEulerAngles = angle;
robotGuardian.transform.localScale = scale;
RobotGuardian robotScript = robotGuardian.GetComponent<RobotGuardian>();
robotScript.OnSpawn();
robotScript.SetPathId(pathId);
return robotGuardian;
}
[ClientRpc]
public void HudMessage(int index)
{
EventDispatcher.TriggerEvent("PromptMessage", index);
}
[ClientRpc]
public void Message(string text, string clipName)
{
EventDispatcher.TriggerEvent("Message", text, clipName);
}
[ClientRpc]
public void ShowTeachUI(int index)
{
EventDispatcher.TriggerEvent("ShowTeachUI", index);
}
[Server]
public GameObject CreateEliteSpiderPre(Vector3 pos, Vector3 angle, Vector3 scale)
{
GameObject eliteSpider = Instantiate(EliteSpiderPre);
NetworkServer.Spawn(eliteSpider);
eliteSpider.transform.position = pos;
eliteSpider.transform.localEulerAngles = angle;
eliteSpider.transform.localScale = scale;
eliteSpider.GetComponent<EliteSpider>().OnSpawn();
return eliteSpider;
}
[Server]
public GameObject CreateRobotMesh(Vector3 pos, Vector3 angle, Vector3 scale)
{
GameObject robotMesh = Instantiate(RobotMechPre);
NetworkServer.Spawn(robotMesh);
robotMesh.transform.position = pos;
robotMesh.transform.localEulerAngles = angle;
robotMesh.transform.localScale = scale;
robotMesh.GetComponent<RobotMech>().OnSpawn();
return robotMesh;
}
/// <summary>
/// 创建幻影者
/// </summary>
/// <param name="pos"></param>
/// <param name="angle"></param>
/// <returns></returns>
[Server]
public GameObject CreateShadow(Vector3 pos, Vector3 angle, Vector3 scale)
{
GameObject Shadow = Instantiate(ShadowPre);
NetworkServer.Spawn(Shadow);
Shadow.transform.position = pos;
Shadow.transform.localEulerAngles = angle;
Shadow.transform.localScale = scale;
Shadow shadow = Shadow.GetComponent<Shadow>();
NowShadow = shadow;
shadow.OnSpawn();
return Shadow;
}
/// <summary>
/// 创建幻影者分身
/// </summary>
/// <param name="pos"></param>
/// <param name="angle"></param>
/// <returns></returns>
public GameObject CreateShadowCast(Vector3 pos, Vector3 angle, Vector3 scale)
{
GameObject Shadow = Instantiate(ShadowCastPre);
NetworkServer.Spawn(Shadow);
Shadow.transform.position = pos;
Shadow.transform.localEulerAngles = angle;
Shadow.transform.localScale = scale;
ShadowCast shadow = Shadow.GetComponent<ShadowCast>();
shadow.Init(NowShadow.OriginHealth, NowShadow.Health);
return Shadow;
}
[Server]
public GameObject CreateBoos(Vector3 pos, Vector3 angle, Vector3 scale, string pathId)
{
GameObject boss = Instantiate(BossPre);
NetworkServer.Spawn(boss);
boss.transform.position = pos;
boss.transform.localEulerAngles = angle;
boss.transform.localScale = scale;
Boss bossScript = boss.GetComponent<Boss>();
bossScript.OnSpawn();
bossScript.SetPathId(pathId);
return boss;
}
[Command(requiresAuthority = false)]
public void CreateGameStartPoint()
{
Vector3 pos = tempDescInfos[0].Positions[0];
GameObject point = Instantiate(gameStartPointPre);
NetworkServer.Spawn(point);
point.transform.position = pos;
// point.transform.position = new Vector3(5.55f, 0, 2.19f);//beijing
}
[Server]
// 创建苍蝇
public GameObject CreateEsky(Vector3 pos, Vector3 angle, Vector3 scale, string pathId)
{
GameObject Esky = Instantiate(EskyPre);
NetworkServer.Spawn(Esky);
Esky.transform.position = pos;
Esky.transform.localEulerAngles = angle;
Esky.transform.localScale = scale;
Esky eskyScript = Esky.GetComponent<Esky>();
eskyScript.OnSpawn();
eskyScript.SetPathId(pathId);
return Esky;
}
[Server]
public GameObject CreateEskyClone(Vector3 pos, Vector3 angle)
{
GameObject EskyClone = Instantiate(EskyClonePre);
NetworkServer.Spawn(EskyClone);
EskyClone.transform.position = pos;
EskyClone.transform.localEulerAngles = angle;
EskyClone eskyScript = EskyClone.GetComponent<EskyClone>();
eskyScript.OnSpawn();
return EskyClone;
}
[Server]
//创建炮台
public GameObject GenerateTurret(Vector3 pos, Vector3 scale, Vector3 angle)
{
GameObject turret = Instantiate(TurretPre);
NetworkServer.Spawn(turret);
turret.transform.position = pos;
turret.transform.localScale = scale;
turret.transform.localEulerAngles = angle;
return turret;
}
public void CreateProp(PropType propType, Vector3 pos)
{
switch (propType)
{
case PropType.BloodBag:
CreateBloodBag(pos);
break;
case PropType.EnergyMask:
CreateShield(pos);
break;
case PropType.AtkBuff:
CreateAtkBuff(pos);
break;
case PropType.DefenseBuff:
CreateDeeBuff(pos);
break;
case PropType.EnergyPump:
GenerateEnergyPump(pos);
break;
}
}
[Server]
public void CreateItemProp(int index, Vector3 pos, int amount = 1)
{
if (index < 500)
{
//武器
CreateWeaponProp((WeaponType)(index), pos, amount);
}
else if (index > 500 && index < 1000)
{
//道具
CreateProp((PropType)(index), pos);
}
}
//创建蜘蛛
[Server]
public GameObject CreateSpider(Vector3 pos, Vector3 angle, Vector3 scale, string pathId = "")
{
GameObject Spider = Instantiate(SpiderPre);
NetworkServer.Spawn(Spider);
Spider.transform.position = pos;
Spider.transform.localEulerAngles = angle;
Spider.transform.localScale = scale;
Spider.GetComponent<Spider>().OnSpawn();
Spider.GetComponent<Spider>().SetPathId(pathId);
return Spider;
}
[Server]
public GameObject CreateSpiderClone(Vector3 pos, Vector3 angle)
{
GameObject SpiderClone = Instantiate(SpiderClonePre);
NetworkServer.Spawn(SpiderClone);
SpiderClone.transform.position = pos;
SpiderClone.transform.localEulerAngles = angle;
SpiderClone.GetComponent<SpiderClone>().OnSpawn();
return SpiderClone;
}
//创建落石特效
[Server]
public GameObject GenerateRockfall(Vector3 pos, Vector3 angle)
{
GameObject Rockfall = Instantiate(RockfallPre);
Rockfall.transform.position = pos;
Rockfall.transform.localEulerAngles = angle;
NetworkServer.Spawn(Rockfall);
return Rockfall;
}
[Server]
public GameObject CreateCrack(Vector3 pos, Vector3 angle)
{
GameObject Crack = Instantiate(CrackPre);
NetworkServer.Spawn(Crack);
Crack.transform.position = new Vector3(pos.x, pos.y, pos.z);
Crack.transform.localEulerAngles = angle;
return Crack;
}
[Server]
public void CreatePortal(Vector3 pos, float angleY, int amount, float interval, bool isActive, EnemyType type)
{
GameObject portal = Instantiate(CrackPre);
NetworkServer.Spawn(portal);
portal.transform.position = pos;
portal.transform.localEulerAngles = new Vector3(0, angleY, 0);
portal.GetComponent<Portal>().Init(amount, interval, isActive, type);
}
// 创建传送门
[Server]
public GameObject SpwanCrack(Transform pos)
{
GameObject Crack = Instantiate(CrackPre);
NetworkServer.Spawn(Crack);
Crack.transform.position = new Vector3(pos.position.x, pos.position.y, pos.position.z);
return Crack;
}
public bool EnemyDie()
{
if (AllEnemyAmount > 0)
AllEnemyAmount--;
if (AllEnemyAmount == 0)
{
EnemyAmount = 0;
return true;
}
return false;
}
// 获取第一个玩家
public Transform GetPlayer1()
{
Transform player = null;
if (MRNetworkManager.Ins.roomSlots.Count > 0)
{
player = MRNetworkManager.Ins.roomSlots[0].transform;
}
return player;
}
public Transform GetPlayer(int index)
{
NetworkRoomPlayer roomPlayer = null;
roomPlayer = MRNetworkManager.Ins.roomSlots[index];
Transform play = roomPlayer.transform;
return play;
}
public int GetRandomPlayerIndex()
{
int index = 0;
//怪物随机选取目标 只取一次
index = Random.Range(0, MRNetworkManager.Ins.roomSlots.Count);
return index;
}
/// <summary>
/// 创建护盾
/// </summary>
[Command(requiresAuthority = false)]
public void CreateShield(Vector3 pos)
{
GameObject shield = Instantiate(ShieldPre);
NetworkServer.Spawn(shield);
shield.transform.position = new Vector3(pos.x, 0, pos.z);
Shield shieldScript = shield.GetComponent<Shield>();
shieldScript.Id = ShieldId;
Shields.Add(ShieldId, shieldScript);
ShieldId++;
}
/// <summary>
/// 删除护盾
/// </summary>
public void DelShield(int id)
{
Shield shield = Shields[id];
if (shield != null)
{
Shields.Remove(id);
}
}
/// <summary>
/// 创建攻击BUFF
/// </summary>
/// <param name="pos"></param>
[Command(requiresAuthority = false)]
public void CreateAtkBuff(Vector3 pos)
{
GameObject atkBuff = Instantiate(AtkBuffPre);
NetworkServer.Spawn(atkBuff);
atkBuff.transform.position = new Vector3(pos.x, 0, pos.z);
}
/// <summary>
/// 创建攻击BUFF
/// </summary>
/// <param name="pos"></param>
[Command(requiresAuthority = false)]
public void CreateDeeBuff(Vector3 pos)
{
GameObject deeBuff = Instantiate(deffBuffPre);
NetworkServer.Spawn(deeBuff);
deeBuff.transform.position = new Vector3(pos.x, 0, pos.z);
}
/// <summary>
/// 创建血包
/// </summary>
[Command(requiresAuthority = false)]
public void CreateBloodBag(Vector3 pos)
{
GameObject bloodBag = Instantiate(BloodBagPre);
NetworkServer.Spawn(bloodBag);
bloodBag.transform.position = new Vector3(pos.x, 0, pos.z);
}
/// <summary>
/// 创建武器道具
/// </summary>
[Command(requiresAuthority = false)]
public void CreateWeaponProp(WeaponType type, Vector3 pos, int amount)
{
GameObject prop = Instantiate(WeaponPropPre);
NetworkServer.Spawn(prop);
prop.GetComponent<WeaponProp>().Init(type, amount);
prop.transform.position = pos;
}
/// <summary>
/// 找到有玩家x在里面的护盾
/// </summary>
/// <param name="playerIndex"></param>
/// <returns></returns>
public int FindPlayerInShield(int playerIndex)
{
int res = -1;
foreach (Shield shield in Shields.Values)
{
float dis = MathExtension.GetDistanceXOZ(MRNetworkManager.Ins.roomSlots[playerIndex].transform.position, shield.transform.position);
if (dis <= 2.5f)
{
res = shield.Id;
break;
}
}
return res;
}
/// <summary>
/// 判断玩家x是否在护盾内
/// </summary>
/// <param name="playerIndex"></param>
/// <returns></returns>
public bool IsPlayerInShield(int playerIndex = 0)
{
bool res = false;
int find = FindPlayerInShield(playerIndex);
if (find != -1)
{
res = true;
}
return res;
}
/// <summary>
/// 根据位置获取能攻击的护盾
/// </summary>
/// <param name="point"></param>
/// <param name="playerIndex"></param>
/// <param name="attackArea"></param>
/// <returns></returns>
public Shield GetCanAttackShield(Vector3 point, int playerIndex, float attackArea)
{
Shield res = null;
int find = FindPlayerInShield(playerIndex);
if (find != -1)
{
float dis = MathExtension.GetDistanceXOZ(Shields[find].transform.position, point);
if (dis > 2.5f && dis < 2.5f + attackArea)
{
res = Shields[find];
}
}
return res;
}
/// <summary>
/// 判断是否能攻击护盾
/// </summary>
public bool IsCanAttackShield(Transform enemy, int playerIndex, float attackArea)
{
bool res = false;
Shield find = GetCanAttackShield(enemy.position, playerIndex, attackArea);
res = find == null ? false : true;
return res;
}
/// <summary>
/// 判断是否能攻击玩家
/// </summary>
/// <param name="playerIndex"></param>
/// <returns></returns>
public bool IsCanAttackPlayer(Transform enemy, int playerIndex, float attackArea)
{
bool res = false;
Transform player = MRNetworkManager.Ins.roomSlots[playerIndex].transform;
float dis = MathExtension.GetDistanceXOZ(player.position, enemy.transform.position);
if (dis <= attackArea)
{
res = true;
}
return res;
}
}