WolfActGrid.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Newtonsoft.Json;
  5. /**
  6. 狼的行动区域,为了避免狼的行动目的坐标重合的问题。
  7. */
  8. public class WolfActGrid : MonoBehaviour
  9. {
  10. [SerializeField] TextAsset jsonText;
  11. JsonConfig config;
  12. [System.NonSerialized] public AreaMatrix areaMatrix = new AreaMatrix();
  13. [SerializeField] Material[] sphereMaterials;
  14. public static WolfActGrid ins;
  15. //调试绘制模式-手动开关
  16. bool debugDrawing = false;
  17. void Awake()
  18. {
  19. ins = this;
  20. areaMatrix.wolfActGrid = this;
  21. config = JsonConfig.Load(jsonText.text);
  22. loadAreaMatrix();
  23. // createAreaMatrix();
  24. }
  25. //从配置中加载地域矩阵(前提是有保存在json配置文件内)
  26. void loadAreaMatrix() {
  27. List<List<Vector3>> posMatrix = areaMatrix.posMatrix = config.GetPosMatrix();
  28. config.SetPosMatrixNull();
  29. for (int r = 0; r < posMatrix.Count; r++) {
  30. for (int c = 0; c < posMatrix[r].Count; c++) {
  31. Vector3 pos = posMatrix[r][c];
  32. DebugDrawSphere(pos, r, c);
  33. }
  34. }
  35. }
  36. //动态创建地域矩阵
  37. void createAreaMatrix() {
  38. float circleRadius = 0.6f;
  39. Vector3 standardPosition = transform.position;
  40. Vector3 standardPointer = transform.forward;
  41. float minAngleY = -20f;
  42. float maxAngleY = 23f;
  43. for (float distance = 8.5f; distance <= 50f; distance += circleRadius * 2) {
  44. List<Vector3> posList = new List<Vector3>();
  45. areaMatrix.posMatrix.Add(posList);
  46. float sinValue = circleRadius / distance;
  47. float deltaAngle = 2f * Mathf.Asin(sinValue) / Mathf.PI * 180f;
  48. for (int col = 0; ; col++) {
  49. float angleY = minAngleY + deltaAngle * col;
  50. if (angleY > maxAngleY) break;
  51. Vector3 pointer = Quaternion.AngleAxis(angleY, Vector3.up) * standardPointer;
  52. Vector3 pointerWithLen = pointer * distance;
  53. Vector3 newPos = standardPosition + pointerWithLen;
  54. #region 射线检测是否被树遮挡
  55. float checkRayDistance = 60f;
  56. Vector3 rayPos = newPos;
  57. Vector3 rayDir = Quaternion.AngleAxis(180, Vector3.up) * pointer;
  58. if (Physics.Raycast(rayPos, rayDir, checkRayDistance, LayerMask.GetMask("Test"))) {
  59. continue;
  60. }
  61. Vector3 pointerWithLen1 = Quaternion.AngleAxis(-deltaAngle / 3f, Vector3.up) * pointerWithLen;
  62. Vector3 rayPos1 = standardPosition + pointerWithLen1;
  63. Vector3 rayDir1 = Quaternion.AngleAxis(180, Vector3.up) * pointerWithLen1;
  64. if (Physics.Raycast(rayPos1, rayDir1, checkRayDistance, LayerMask.GetMask("Test"))) {
  65. continue;
  66. }
  67. Vector3 pointerWithLen2 = Quaternion.AngleAxis(deltaAngle / 3f, Vector3.up) * pointerWithLen;
  68. Vector3 rayPos2 = standardPosition + pointerWithLen2;
  69. Vector3 rayDir2 = Quaternion.AngleAxis(180, Vector3.up) * pointerWithLen2;
  70. if (Physics.Raycast(rayPos2, rayDir2, checkRayDistance, LayerMask.GetMask("Test"))) {
  71. continue;
  72. }
  73. #endregion
  74. posList.Add(newPos);
  75. DebugDrawSphere(newPos, areaMatrix.posMatrix.Count - 1, posList.Count - 1);
  76. }
  77. }
  78. }
  79. void DebugDrawSphere(Vector3 pos, int r, int c) {
  80. if (!debugDrawing) return;
  81. GameObject sphere = transform.Find("Sphere").gameObject;
  82. GameObject o = GameObject.Instantiate(sphere, pos, Quaternion.identity, transform);
  83. o.name = r + "_" + c;
  84. o.SetActive(true);
  85. }
  86. public void DebugOccupySphere(string name, bool occupy) {
  87. if (!debugDrawing) return;
  88. transform.Find(name).GetComponent<MeshRenderer>().material = occupy ? sphereMaterials[1] : sphereMaterials[0];
  89. }
  90. //提供给狼的接口,扑击结束后,跑回的地点
  91. int runBackPointIndex = -1;
  92. public Vector3 GetRunBackPointAfterPounce() {
  93. if (runBackPointIndex == -1) runBackPointIndex = Random.Range(0, 2);
  94. runBackPointIndex++;
  95. return this.transform.Find("RunBackPoint" + (runBackPointIndex % 2)).position;
  96. }
  97. public class AreaMatrix {
  98. public List<List<Vector3>> posMatrix = new List<List<Vector3>>();
  99. //格式:"行_列"
  100. public Dictionary<object, string> occupyDC = new Dictionary<object, string>();
  101. public WolfActGrid wolfActGrid;
  102. //计算水平距离
  103. float calDis(Vector3 p1, Vector3 p2) {
  104. return Mathf.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.z - p2.z) * (p1.z - p2.z));
  105. }
  106. // 占用距离最近的格子,如果最近的被占用则广度优先寻找附近较近的格子
  107. public bool occupyPos(Vector3 p, object obj) {
  108. float minDis = float.MaxValue;
  109. int bestR = 0;
  110. int bestC = 0;
  111. for (int r = 0; r < posMatrix.Count; r++) {
  112. for (int c = 0; c < posMatrix[r].Count; c++) {
  113. Vector3 pos = posMatrix[r][c];
  114. float dis = calDis(pos, p);
  115. if (dis < minDis) {
  116. minDis = dis;
  117. bestR = r;
  118. bestC = c;
  119. }
  120. }
  121. }
  122. object cur_occupy_obj = checkOccupy(bestR, bestC);
  123. //如果目标格子被其它对象占用,则过渡优先寻找附近的格子,因为矩阵是扇形,目前的fbs有偏差,但无妨
  124. if (cur_occupy_obj != null && !obj.Equals(cur_occupy_obj)) {
  125. int sr = bestR;
  126. int sc = bestC;
  127. List<string> openList = new List<string>();
  128. openList.Add(sr + "_" + sc);
  129. int scanIndex = 1;
  130. bool breakBFS = false;
  131. while (true) {
  132. int i = 0;
  133. while (i < 8) {
  134. i++;
  135. if (i == 1) { sc++; }
  136. if (i == 2) { sr--; }
  137. if (i == 3) { sc--; }
  138. if (i == 4) { sc--; }
  139. if (i == 5) { sr++; }
  140. if (i == 6) { sr++; }
  141. if (i == 7) { sc++; }
  142. if (i == 8) { sc++; }
  143. if (sr >= 0 && sr < posMatrix.Count && sc >= 0 && sc < posMatrix[sr].Count) {
  144. string keyName = sr + "_" + sc;
  145. if (!openList.Contains(keyName)) {
  146. object now_occupy_obj = checkOccupy(sr, sc);
  147. if (now_occupy_obj == null || obj.Equals(now_occupy_obj)) {
  148. bestR = sr;
  149. bestC = sc;
  150. breakBFS = true;
  151. break;
  152. }
  153. //加入
  154. openList.Add(keyName);
  155. }
  156. }
  157. }
  158. if (breakBFS) break;
  159. if (scanIndex < openList.Count) {
  160. string[] str = openList[scanIndex].Split('_');
  161. scanIndex++;
  162. sr = int.Parse(str[0]);
  163. sc = int.Parse(str[1]);
  164. } else {
  165. return false;
  166. }
  167. }
  168. }
  169. //找到最佳的格子
  170. Vector3 bestPoint = posMatrix[bestR][bestC];
  171. p.x = bestPoint.x;
  172. p.z = bestPoint.z;
  173. //释放自己以前占用的格子
  174. releaseOccupy(obj);
  175. //占用目标格子
  176. Occupy(bestR, bestC, obj);
  177. return true;
  178. }
  179. public object checkOccupy(int r, int c) {
  180. string keyName = r + "_" + c;
  181. foreach (var item in occupyDC)
  182. {
  183. if (item.Value.Equals(keyName)) return item.Key;
  184. }
  185. return null;
  186. }
  187. public void releaseOccupy(object obj) {
  188. string keyName = null;
  189. occupyDC.TryGetValue(obj, out keyName);
  190. if (keyName == null) {
  191. return;
  192. }
  193. occupyDC.Remove(obj);
  194. wolfActGrid.DebugOccupySphere(keyName, false);
  195. }
  196. public void Occupy(int r, int c, object obj) {
  197. string keyName = r + "_" + c;
  198. occupyDC[obj] = keyName;
  199. wolfActGrid.DebugOccupySphere(keyName, true);
  200. if (!wolfActGrid.debugDrawing) return;
  201. if (obj.GetType().Equals(typeof(Wolf))) {
  202. Wolf wolf = (Wolf) obj;
  203. WolfLineRender wolfLineRender = wolf.GetComponentInChildren<WolfLineRender>();
  204. if (!wolfLineRender) {
  205. GameObject prefab = wolfActGrid.transform.Find("WolfLineRender").gameObject;
  206. GameObject o = GameObject.Instantiate(prefab, wolf.transform.position + Vector3.up * 0.8f, Quaternion.identity, wolf.transform);
  207. wolfLineRender = o.GetComponent<WolfLineRender>();
  208. o.SetActive(true);
  209. }
  210. wolfLineRender.SetDestination(posMatrix[r][c]);
  211. }
  212. }
  213. }
  214. class JsonConfig {
  215. public string posMatrix = null;
  216. //清空,避免占用内存
  217. public void SetPosMatrixNull() {
  218. posMatrix = null;
  219. }
  220. public List<List<Vector3>> GetPosMatrix() {
  221. string[] lines = posMatrix.Split('\n');
  222. List<List<Vector3>> list = new List<List<Vector3>>();
  223. foreach (var line in lines)
  224. {
  225. if (line.Trim().Length == 0) continue;
  226. string[] vectorStrs = line.Split(' ');
  227. List<Vector3> childList = new List<Vector3>();
  228. foreach (var vectorStr in vectorStrs)
  229. {
  230. string[] valStrs = vectorStr.Split('_');
  231. Vector3 vec = new Vector3(
  232. float.Parse(valStrs[0]),
  233. float.Parse(valStrs[1]),
  234. float.Parse(valStrs[2])
  235. );
  236. childList.Add(vec);
  237. }
  238. list.Add(childList);
  239. }
  240. return list;
  241. }
  242. public void SetPosMatrix(List<List<Vector3>> list) {
  243. posMatrix = "";
  244. for (int i = 0; i < list.Count; i++) {
  245. for (int j = 0; j < list[i].Count; j++) {
  246. Vector3 pos = list[i][j];
  247. posMatrix += pos.x + "_" + pos.y + "_" + pos.z;
  248. if (j < list[i].Count - 1) posMatrix += " ";
  249. }
  250. if (i < list.Count - 1) posMatrix += "\n";
  251. };
  252. }
  253. public void Write() {
  254. string filePath =
  255. "E:\\UnityProject\\SmartBow\\Assets\\BowArrow\\Scenes\\GameChallengeScene\\WolfActGrid.json";
  256. if (!System.IO.File.Exists(filePath)) {
  257. Debug.LogError("JsonConfig-File-NotExist");
  258. return;
  259. }
  260. try
  261. {
  262. System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath);
  263. writer.Write(JsonConvert.SerializeObject(this));
  264. writer.Close();
  265. }
  266. catch (System.Exception e)
  267. {
  268. Debug.LogError("JsonConfig-Write-Fail");
  269. Debug.LogError(e.Message);
  270. }
  271. }
  272. public static JsonConfig Load(string jsonText) {
  273. JsonConfig jsonConfig = JsonConvert.DeserializeObject<JsonConfig>(jsonText);
  274. if (jsonConfig == null) jsonConfig = new JsonConfig();
  275. return jsonConfig;
  276. }
  277. }
  278. [ContextMenu("SaveJsonConfig")]
  279. void SaveJsonConfig() {
  280. config.SetPosMatrix(areaMatrix.posMatrix);
  281. config.Write();
  282. }
  283. }