WolfActGrid.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. public class AreaMatrix {
  91. public List<List<Vector3>> posMatrix = new List<List<Vector3>>();
  92. //格式:"行_列"
  93. public Dictionary<object, string> occupyDC = new Dictionary<object, string>();
  94. public WolfActGrid wolfActGrid;
  95. //计算水平距离
  96. float calDis(Vector3 p1, Vector3 p2) {
  97. return Mathf.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.z - p2.z) * (p1.z - p2.z));
  98. }
  99. // 占用距离最近的格子,如果最近的被占用则广度优先寻找附近较近的格子
  100. public bool occupyPos(Vector3 p, object obj) {
  101. float minDis = float.MaxValue;
  102. int bestR = 0;
  103. int bestC = 0;
  104. for (int r = 0; r < posMatrix.Count; r++) {
  105. for (int c = 0; c < posMatrix[r].Count; c++) {
  106. Vector3 pos = posMatrix[r][c];
  107. float dis = calDis(pos, p);
  108. if (dis < minDis) {
  109. minDis = dis;
  110. bestR = r;
  111. bestC = c;
  112. }
  113. }
  114. }
  115. object cur_occupy_obj = checkOccupy(bestR, bestC);
  116. //如果目标格子被其它对象占用,则过渡优先寻找附近的格子,因为矩阵是扇形,目前的fbs有偏差,但无妨
  117. if (cur_occupy_obj != null && !obj.Equals(cur_occupy_obj)) {
  118. int sr = bestR;
  119. int sc = bestC;
  120. List<string> openList = new List<string>();
  121. openList.Add(sr + "_" + sc);
  122. int scanIndex = 1;
  123. bool breakBFS = false;
  124. while (true) {
  125. int i = 0;
  126. while (i < 8) {
  127. i++;
  128. if (i == 1) { sc++; }
  129. if (i == 2) { sr--; }
  130. if (i == 3) { sc--; }
  131. if (i == 4) { sc--; }
  132. if (i == 5) { sr++; }
  133. if (i == 6) { sr++; }
  134. if (i == 7) { sc++; }
  135. if (i == 8) { sc++; }
  136. if (sr >= 0 && sr < posMatrix.Count && sc >= 0 && sc < posMatrix[sr].Count) {
  137. string keyName = sr + "_" + sc;
  138. if (!openList.Contains(keyName)) {
  139. object now_occupy_obj = checkOccupy(sr, sc);
  140. if (now_occupy_obj == null || obj.Equals(now_occupy_obj)) {
  141. bestR = sr;
  142. bestC = sc;
  143. breakBFS = true;
  144. break;
  145. }
  146. //加入
  147. openList.Add(keyName);
  148. }
  149. }
  150. }
  151. if (breakBFS) break;
  152. if (scanIndex < openList.Count) {
  153. string[] str = openList[scanIndex].Split('_');
  154. scanIndex++;
  155. sr = int.Parse(str[0]);
  156. sc = int.Parse(str[1]);
  157. } else {
  158. return false;
  159. }
  160. }
  161. }
  162. //找到最佳的格子
  163. Vector3 bestPoint = posMatrix[bestR][bestC];
  164. p.x = bestPoint.x;
  165. p.z = bestPoint.z;
  166. //释放自己以前占用的格子
  167. releaseOccupy(obj);
  168. //占用目标格子
  169. Occupy(bestR, bestC, obj);
  170. return true;
  171. }
  172. public object checkOccupy(int r, int c) {
  173. string keyName = r + "_" + c;
  174. foreach (var item in occupyDC)
  175. {
  176. if (item.Value.Equals(keyName)) return item.Key;
  177. }
  178. return null;
  179. }
  180. public void releaseOccupy(object obj) {
  181. string keyName = null;
  182. occupyDC.TryGetValue(obj, out keyName);
  183. if (keyName == null) {
  184. return;
  185. }
  186. occupyDC.Remove(obj);
  187. wolfActGrid.DebugOccupySphere(keyName, false);
  188. }
  189. public void Occupy(int r, int c, object obj) {
  190. string keyName = r + "_" + c;
  191. occupyDC[obj] = keyName;
  192. wolfActGrid.DebugOccupySphere(keyName, true);
  193. if (!wolfActGrid.debugDrawing) return;
  194. if (obj.GetType().Equals(typeof(Wolf))) {
  195. Wolf wolf = (Wolf) obj;
  196. WolfLineRender wolfLineRender = wolf.GetComponentInChildren<WolfLineRender>();
  197. if (!wolfLineRender) {
  198. GameObject prefab = wolfActGrid.transform.Find("WolfLineRender").gameObject;
  199. GameObject o = GameObject.Instantiate(prefab, wolf.transform.position + Vector3.up * 0.8f, Quaternion.identity, wolf.transform);
  200. wolfLineRender = o.GetComponent<WolfLineRender>();
  201. o.SetActive(true);
  202. }
  203. wolfLineRender.SetDestination(posMatrix[r][c]);
  204. }
  205. }
  206. }
  207. class JsonConfig {
  208. public string posMatrix = null;
  209. //清空,避免占用内存
  210. public void SetPosMatrixNull() {
  211. posMatrix = null;
  212. }
  213. public List<List<Vector3>> GetPosMatrix() {
  214. string[] lines = posMatrix.Split('\n');
  215. List<List<Vector3>> list = new List<List<Vector3>>();
  216. foreach (var line in lines)
  217. {
  218. if (line.Trim().Length == 0) continue;
  219. string[] vectorStrs = line.Split(' ');
  220. List<Vector3> childList = new List<Vector3>();
  221. foreach (var vectorStr in vectorStrs)
  222. {
  223. string[] valStrs = vectorStr.Split('_');
  224. Vector3 vec = new Vector3(
  225. float.Parse(valStrs[0]),
  226. float.Parse(valStrs[1]),
  227. float.Parse(valStrs[2])
  228. );
  229. childList.Add(vec);
  230. }
  231. list.Add(childList);
  232. }
  233. return list;
  234. }
  235. public void SetPosMatrix(List<List<Vector3>> list) {
  236. posMatrix = "";
  237. for (int i = 0; i < list.Count; i++) {
  238. for (int j = 0; j < list[i].Count; j++) {
  239. Vector3 pos = list[i][j];
  240. posMatrix += pos.x + "_" + pos.y + "_" + pos.z;
  241. if (j < list[i].Count - 1) posMatrix += " ";
  242. }
  243. if (i < list.Count - 1) posMatrix += "\n";
  244. };
  245. }
  246. public void Write() {
  247. string filePath =
  248. "E:\\UnityProject\\SmartBow\\Assets\\BowArrow\\Scenes\\GameChallengeScene\\WolfActGrid.json";
  249. if (!System.IO.File.Exists(filePath)) {
  250. Debug.LogError("JsonConfig-File-NotExist");
  251. return;
  252. }
  253. try
  254. {
  255. System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath);
  256. writer.Write(JsonConvert.SerializeObject(this));
  257. writer.Close();
  258. }
  259. catch (System.Exception e)
  260. {
  261. Debug.LogError("JsonConfig-Write-Fail");
  262. Debug.LogError(e.Message);
  263. }
  264. }
  265. public static JsonConfig Load(string jsonText) {
  266. JsonConfig jsonConfig = JsonConvert.DeserializeObject<JsonConfig>(jsonText);
  267. if (jsonConfig == null) jsonConfig = new JsonConfig();
  268. return jsonConfig;
  269. }
  270. }
  271. [ContextMenu("SaveJsonConfig")]
  272. void SaveJsonConfig() {
  273. config.SetPosMatrix(areaMatrix.posMatrix);
  274. config.Write();
  275. }
  276. }