BlockManager.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Vec2, UITransform, find } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('BlockManager')
  4. export class BlockManager extends Component {
  5. // 预制体数组,存储5个预制体
  6. @property([Prefab])
  7. public blockPrefabs: Prefab[] = [];
  8. // 网格容器节点
  9. @property({
  10. type: Node,
  11. tooltip: '拖拽GridContainer节点到这里'
  12. })
  13. public gridContainer: Node = null;
  14. // 已经生成的块
  15. private blocks: Node[] = [];
  16. // 当前拖拽的块
  17. private currentDragBlock: Node | null = null;
  18. // 拖拽起始位置
  19. private startPos = new Vec2();
  20. // 块的起始位置
  21. private blockStartPos: Vec3 = new Vec3();
  22. // 网格占用情况,用于控制台输出
  23. private gridOccupationMap: number[][] = [];
  24. // 网格行数和列数
  25. private readonly GRID_ROWS = 6;
  26. private readonly GRID_COLS = 11;
  27. // 是否已初始化网格信息
  28. private gridInitialized = false;
  29. // 存储网格节点信息
  30. private gridNodes: Node[][] = [];
  31. // 网格间距
  32. private gridSpacing = 54;
  33. // 不参与占用的节点名称列表
  34. private readonly NON_BLOCK_NODES: string[] = ['Weapon'];
  35. // 临时保存方块的原始占用格子
  36. private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
  37. start() {
  38. // 如果没有指定GridContainer,尝试找到它
  39. if (!this.gridContainer) {
  40. this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
  41. if (!this.gridContainer) {
  42. console.error('找不到GridContainer节点');
  43. return;
  44. }
  45. }
  46. // 初始化网格信息
  47. this.initGridInfo();
  48. // 初始化网格占用情况
  49. this.initGridOccupationMap();
  50. // 生成随机的三个块
  51. this.generateRandomBlocks();
  52. }
  53. // 初始化网格信息
  54. initGridInfo() {
  55. if (!this.gridContainer || this.gridInitialized) return;
  56. // 创建二维数组存储网格节点
  57. this.gridNodes = [];
  58. for (let row = 0; row < this.GRID_ROWS; row++) {
  59. this.gridNodes[row] = [];
  60. }
  61. // 遍历所有网格节点,将它们放入二维数组
  62. for (let i = 0; i < this.gridContainer.children.length; i++) {
  63. const grid = this.gridContainer.children[i];
  64. if (grid.name.startsWith('Grid_')) {
  65. // 从节点名称解析行列信息,例如Grid_2_3表示第2行第3列
  66. const parts = grid.name.split('_');
  67. if (parts.length === 3) {
  68. const row = parseInt(parts[1]);
  69. const col = parseInt(parts[2]);
  70. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  71. this.gridNodes[row][col] = grid;
  72. }
  73. }
  74. }
  75. }
  76. // 计算网格间距
  77. if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
  78. if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
  79. const pos1 = this.gridNodes[0][0].position;
  80. const pos2 = this.gridNodes[1][0].position;
  81. this.gridSpacing = Math.abs(pos2.y - pos1.y);
  82. }
  83. }
  84. this.gridInitialized = true;
  85. }
  86. // 初始化网格占用情况
  87. initGridOccupationMap() {
  88. this.gridOccupationMap = [];
  89. for (let row = 0; row < this.GRID_ROWS; row++) {
  90. const rowArray: number[] = [];
  91. for (let col = 0; col < this.GRID_COLS; col++) {
  92. rowArray.push(0);
  93. }
  94. this.gridOccupationMap.push(rowArray);
  95. }
  96. }
  97. generateRandomBlocks() {
  98. // 清除现有的块
  99. this.clearBlocks();
  100. // 检查是否有预制体可用
  101. if (this.blockPrefabs.length === 0) {
  102. console.error('没有可用的预制体');
  103. return;
  104. }
  105. // 位置偏移量
  106. const offsets = [
  107. new Vec3(-200, 0, 0),
  108. new Vec3(0, 0, 0),
  109. new Vec3(200, 0, 0)
  110. ];
  111. // 生成三个随机块
  112. for (let i = 0; i < 3; i++) {
  113. // 随机选择一个预制体
  114. const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
  115. const prefab = this.blockPrefabs[randomIndex];
  116. // 实例化预制体
  117. const block = instantiate(prefab);
  118. this.node.addChild(block);
  119. // 设置位置
  120. block.position = offsets[i];
  121. // 添加到块数组
  122. this.blocks.push(block);
  123. // 添加触摸事件
  124. this.setupDragEvents(block);
  125. }
  126. }
  127. setupDragEvents(block: Node) {
  128. // 添加触摸开始事件
  129. block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  130. // 记录当前拖拽的块
  131. this.currentDragBlock = block;
  132. // 记录触摸起始位置
  133. this.startPos = event.getUILocation();
  134. // 记录块的起始位置
  135. this.blockStartPos.set(block.position);
  136. // 将块置于顶层
  137. block.setSiblingIndex(this.node.children.length - 1);
  138. // 临时保存方块占用的网格,而不是直接移除
  139. this.tempStoreBlockOccupiedGrids(block);
  140. }, this);
  141. // 添加触摸移动事件
  142. block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  143. if (!this.currentDragBlock) return;
  144. // 计算触摸点位移
  145. const location = event.getUILocation();
  146. const deltaX = location.x - this.startPos.x;
  147. const deltaY = location.y - this.startPos.y;
  148. // 更新块的位置
  149. this.currentDragBlock.position = new Vec3(
  150. this.blockStartPos.x + deltaX,
  151. this.blockStartPos.y + deltaY,
  152. this.blockStartPos.z
  153. );
  154. }, this);
  155. // 添加触摸结束事件
  156. block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  157. if (this.currentDragBlock) {
  158. // 尝试将方块放置到网格中
  159. if (!this.tryPlaceBlockToGrid(this.currentDragBlock)) {
  160. // 放置失败,返回原位
  161. this.currentDragBlock.position = this.blockStartPos.clone();
  162. // 恢复方块原来的占用状态
  163. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  164. } else {
  165. // 放置成功,清除临时保存的占用状态
  166. this.clearTempStoredOccupiedGrids(this.currentDragBlock);
  167. }
  168. this.currentDragBlock = null;
  169. }
  170. }, this);
  171. // 添加触摸取消事件
  172. block.on(Node.EventType.TOUCH_CANCEL, () => {
  173. if (this.currentDragBlock) {
  174. // 触摸取消,返回原位
  175. this.currentDragBlock.position = this.blockStartPos.clone();
  176. // 恢复方块原来的占用状态
  177. this.restoreBlockOccupiedGrids(this.currentDragBlock);
  178. this.currentDragBlock = null;
  179. }
  180. }, this);
  181. }
  182. // 临时保存方块占用的网格
  183. tempStoreBlockOccupiedGrids(block: Node) {
  184. // 获取方块占用的网格
  185. const occupiedGrids = block['occupiedGrids'];
  186. if (!occupiedGrids || occupiedGrids.length === 0) return;
  187. // 保存到临时数组
  188. this.tempRemovedOccupiedGrids.push({
  189. block: block,
  190. occupiedGrids: [...occupiedGrids] // 复制一份,避免引用问题
  191. });
  192. // 移除占用标记
  193. for (const grid of occupiedGrids) {
  194. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  195. grid.col >= 0 && grid.col < this.GRID_COLS) {
  196. this.gridOccupationMap[grid.row][grid.col] = 0;
  197. }
  198. }
  199. // 清空方块的占用记录
  200. block['occupiedGrids'] = [];
  201. }
  202. // 恢复方块原来的占用状态
  203. restoreBlockOccupiedGrids(block: Node) {
  204. // 查找临时保存的占用状态
  205. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  206. if (index === -1) return;
  207. const savedItem = this.tempRemovedOccupiedGrids[index];
  208. // 恢复占用标记
  209. for (const grid of savedItem.occupiedGrids) {
  210. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  211. grid.col >= 0 && grid.col < this.GRID_COLS) {
  212. this.gridOccupationMap[grid.row][grid.col] = 1;
  213. }
  214. }
  215. // 恢复方块的占用记录
  216. block['occupiedGrids'] = [...savedItem.occupiedGrids];
  217. // 从临时数组中移除
  218. this.tempRemovedOccupiedGrids.splice(index, 1);
  219. }
  220. // 清除临时保存的占用状态
  221. clearTempStoredOccupiedGrids(block: Node) {
  222. // 查找临时保存的占用状态
  223. const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
  224. if (index === -1) return;
  225. // 从临时数组中移除
  226. this.tempRemovedOccupiedGrids.splice(index, 1);
  227. }
  228. // 获取网格行列索引
  229. getGridRowCol(gridNode: Node): { row: number, col: number } | null {
  230. if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
  231. const parts = gridNode.name.split('_');
  232. if (parts.length === 3) {
  233. const row = parseInt(parts[1]);
  234. const col = parseInt(parts[2]);
  235. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  236. return { row, col };
  237. }
  238. }
  239. return null;
  240. }
  241. // 找到最近的网格节点
  242. findNearestGridNode(position: Vec3): Node {
  243. if (!this.gridContainer || !this.gridInitialized) return null;
  244. let nearestNode: Node = null;
  245. let minDistance = Number.MAX_VALUE;
  246. // 遍历所有网格节点
  247. for (let row = 0; row < this.GRID_ROWS; row++) {
  248. for (let col = 0; col < this.GRID_COLS; col++) {
  249. const grid = this.gridNodes[row][col];
  250. if (grid) {
  251. const distance = Vec3.distance(position, grid.position);
  252. if (distance < minDistance) {
  253. minDistance = distance;
  254. nearestNode = grid;
  255. }
  256. }
  257. }
  258. }
  259. // 增加容错性,放宽距离限制
  260. if (minDistance > this.gridSpacing * 2) {
  261. // 如果距离超过网格间距的4倍,可能是完全偏离了网格区域
  262. if (minDistance > this.gridSpacing * 4) {
  263. return null;
  264. }
  265. }
  266. return nearestNode;
  267. }
  268. // 尝试将方块放置到网格中
  269. tryPlaceBlockToGrid(block: Node): boolean {
  270. if (!this.gridContainer || !this.gridInitialized) return false;
  271. // 获取B1节点
  272. let b1Node = block;
  273. if (block.name !== 'B1') {
  274. // 查找B1节点
  275. b1Node = block.getChildByName('B1');
  276. if (!b1Node) {
  277. return false;
  278. }
  279. }
  280. // 获取方块B1节点在世界坐标中的位置
  281. const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
  282. // 将B1节点的世界坐标转换为GridContainer的本地坐标
  283. const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
  284. // 检查是否在GridContainer范围内
  285. const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
  286. const halfWidth = gridSize.width / 2;
  287. const halfHeight = gridSize.height / 2;
  288. // 增加容错性,放宽边界检查
  289. const tolerance = this.gridSpacing * 0.5;
  290. if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
  291. gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
  292. return false;
  293. }
  294. // 找到最近的网格节点
  295. const nearestGrid = this.findNearestGridNode(gridPos);
  296. if (!nearestGrid) {
  297. // 尝试使用网格行列直接定位
  298. const row = Math.floor((gridPos.y + halfHeight) / this.gridSpacing);
  299. const col = Math.floor((gridPos.x + halfWidth) / this.gridSpacing);
  300. // 检查计算出的行列是否在有效范围内
  301. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  302. const grid = this.gridNodes[row][col];
  303. if (grid) {
  304. return this.tryPlaceBlockToSpecificGrid(block, grid);
  305. }
  306. }
  307. return false;
  308. }
  309. return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
  310. }
  311. // 尝试将方块放置到指定的网格节点
  312. tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
  313. // 获取B1节点
  314. let b1Node = block;
  315. if (block.name !== 'B1') {
  316. b1Node = block.getChildByName('B1');
  317. if (!b1Node) {
  318. return false;
  319. }
  320. }
  321. // 检查方块的所有部分是否会与已占用的格子重叠
  322. if (!this.canPlaceBlockAt(block, targetGrid)) {
  323. return false;
  324. }
  325. // 获取网格节点的中心点世界坐标
  326. const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
  327. // 计算B1节点应该移动到的位置
  328. const targetWorldPos = gridCenterWorldPos.clone();
  329. // 计算根节点需要移动的位置
  330. // 1. 先计算B1节点相对于根节点的偏移
  331. const b1LocalPos = b1Node.position.clone();
  332. // 2. 计算根节点的目标世界坐标
  333. let rootTargetWorldPos;
  334. if (b1Node === block) {
  335. rootTargetWorldPos = targetWorldPos.clone();
  336. } else {
  337. // 如果B1是子节点,需要计算根节点应该在的位置,使B1对准网格中心
  338. rootTargetWorldPos = new Vec3(
  339. targetWorldPos.x - b1LocalPos.x,
  340. targetWorldPos.y - b1LocalPos.y,
  341. targetWorldPos.z
  342. );
  343. }
  344. // 3. 将世界坐标转换为根节点父节点的本地坐标
  345. const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
  346. // 设置方块位置,确保B1节点的中心与网格节点的中心对齐
  347. block.position = rootTargetLocalPos;
  348. // 标记占用的格子
  349. this.markOccupiedPositions(block, targetGrid);
  350. return true;
  351. }
  352. // 获取方块的所有部分节点及其相对坐标
  353. getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
  354. const parts: { node: Node, x: number, y: number }[] = [];
  355. // 添加B1节点本身(根节点)
  356. parts.push({ node: block, x: 0, y: 0 });
  357. // 递归查找所有子节点
  358. this.findBlockParts(block, parts, 0, 0);
  359. return parts;
  360. }
  361. // 递归查找方块的所有部分
  362. findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
  363. // 遍历所有子节点
  364. for (let i = 0; i < node.children.length; i++) {
  365. const child = node.children[i];
  366. // 跳过不参与占用的节点
  367. if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
  368. continue;
  369. }
  370. let x = parentX;
  371. let y = parentY;
  372. // 尝试从节点名称中解析坐标
  373. const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
  374. if (match) {
  375. // 如果节点名称是坐标格式,直接使用
  376. x = parseInt(match[1]);
  377. y = parseInt(match[2]);
  378. result.push({ node: child, x, y });
  379. } else if (child.name.startsWith('B')) {
  380. // 如果是B开头的节点,使用其相对位置
  381. // 计算相对于父节点的位置,并转换为网格单位
  382. const relativeX = Math.round(child.position.x / this.gridSpacing);
  383. const relativeY = -Math.round(child.position.y / this.gridSpacing); // Y轴向下为正
  384. x = parentX + relativeX;
  385. y = parentY + relativeY;
  386. result.push({ node: child, x, y });
  387. }
  388. // 递归处理子节点
  389. this.findBlockParts(child, result, x, y);
  390. }
  391. }
  392. // 检查方块是否可以放置在指定位置
  393. canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
  394. if (!this.gridInitialized) return false;
  395. // 获取目标网格的行列索引
  396. const targetRowCol = this.getGridRowCol(targetGrid);
  397. if (!targetRowCol) return false;
  398. // 获取方块的所有部分
  399. const parts = this.getBlockParts(block);
  400. // 检查每个部分是否与已占用的格子重叠
  401. for (const part of parts) {
  402. // 计算在网格中的行列位置
  403. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  404. const col = targetRowCol.col + part.x; // X轴向右为正
  405. // 检查是否超出网格范围
  406. if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
  407. return false;
  408. }
  409. // 检查该位置是否已被占用
  410. if (this.gridOccupationMap[row][col] === 1) {
  411. return false;
  412. }
  413. }
  414. return true;
  415. }
  416. // 标记方块占用的格子
  417. markOccupiedPositions(block: Node, targetGrid: Node) {
  418. if (!this.gridInitialized) return;
  419. // 获取目标网格的行列索引
  420. const targetRowCol = this.getGridRowCol(targetGrid);
  421. if (!targetRowCol) return;
  422. // 获取方块的所有部分
  423. const parts = this.getBlockParts(block);
  424. // 清除之前的占用记录
  425. block['occupiedGrids'] = [];
  426. // 为每个部分标记占用位置
  427. for (const part of parts) {
  428. // 计算在网格中的行列位置
  429. const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
  430. const col = targetRowCol.col + part.x; // X轴向右为正
  431. // 检查是否在有效范围内
  432. if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
  433. // 更新网格占用情况
  434. this.gridOccupationMap[row][col] = 1;
  435. // 存储方块与网格的关联
  436. block['occupiedGrids'] = block['occupiedGrids'] || [];
  437. block['occupiedGrids'].push({ row, col });
  438. }
  439. }
  440. }
  441. // 移除方块占用的格子
  442. removeBlockFromGrid(block: Node) {
  443. // 获取方块占用的网格
  444. const occupiedGrids = block['occupiedGrids'];
  445. if (!occupiedGrids) return;
  446. // 移除占用标记
  447. for (const grid of occupiedGrids) {
  448. if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
  449. grid.col >= 0 && grid.col < this.GRID_COLS) {
  450. this.gridOccupationMap[grid.row][grid.col] = 0;
  451. }
  452. }
  453. // 清空方块的占用记录
  454. block['occupiedGrids'] = [];
  455. }
  456. clearBlocks() {
  457. // 移除所有已经生成的块
  458. for (const block of this.blocks) {
  459. if (block.isValid) {
  460. // 移除占用的格子
  461. this.removeBlockFromGrid(block);
  462. // 销毁方块
  463. block.destroy();
  464. }
  465. }
  466. this.blocks = [];
  467. // 重置网格占用情况
  468. this.initGridOccupationMap();
  469. }
  470. }