| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108 |
- import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Vec2, UITransform, find, Rect, Label, Color, Size, Contact2DType, Collider2D, IPhysics2DContact } from 'cc';
- const { ccclass, property } = _decorator;
- @ccclass('BlockManager')
- export class BlockManager extends Component {
- // 预制体数组,存储5个预制体
- @property([Prefab])
- public blockPrefabs: Prefab[] = [];
-
- // 网格容器节点
- @property({
- type: Node,
- tooltip: '拖拽GridContainer节点到这里'
- })
- public gridContainer: Node = null;
-
- // 方块容器节点(kuang)
- @property({
- type: Node,
- tooltip: '拖拽kuang节点到这里'
- })
- public kuangContainer: Node = null;
-
- // 金币标签节点
- @property({
- type: Node,
- tooltip: '拖拽CoinLabel节点到这里'
- })
- public coinLabelNode: Node = null;
-
- // 游戏是否已开始
- public gameStarted: boolean = false;
-
- // 玩家金币数量
- private playerCoins: number = 699;
-
- // 方块价格标签映射
- private blockPriceMap: Map<Node, Node> = new Map();
-
- // 已经生成的块
- private blocks: Node[] = [];
- // 当前拖拽的块
- private currentDragBlock: Node | null = null;
- // 拖拽起始位置
- private startPos = new Vec2();
- // 块的起始位置
- private blockStartPos: Vec3 = new Vec3();
- // 网格占用情况,用于控制台输出
- private gridOccupationMap: number[][] = [];
- // 网格行数和列数
- private readonly GRID_ROWS = 6;
- private readonly GRID_COLS = 11;
- // 是否已初始化网格信息
- private gridInitialized = false;
- // 存储网格节点信息
- private gridNodes: Node[][] = [];
- // 网格间距
- private gridSpacing = 54;
- // 不参与占用的节点名称列表
- private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
- // 临时保存方块的原始占用格子
- private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
- // 方块原始位置(在kuang中的位置)
- private originalPositions: Map<Node, Vec3> = new Map();
- // 方块当前所在的区域
- private blockLocations: Map<Node, string> = new Map();
-
- start() {
- // 如果没有指定GridContainer,尝试找到它
- if (!this.gridContainer) {
- this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
- if (!this.gridContainer) {
- console.error('找不到GridContainer节点');
- return;
- }
- }
-
- // 如果没有指定kuangContainer,尝试找到它
- if (!this.kuangContainer) {
- this.kuangContainer = find('Canvas/GameLevelUI/kuang');
- if (!this.kuangContainer) {
- console.error('找不到kuang节点');
- return;
- }
- }
-
- // 如果没有指定coinLabelNode,尝试找到它
- if (!this.coinLabelNode) {
- this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
- if (!this.coinLabelNode) {
- console.error('找不到CoinLabel节点');
- return;
- }
- }
-
- // 确保有PlacedBlocks节点用于存放已放置的方块
- this.ensurePlacedBlocksNode();
-
- // 初始化玩家金币显示
- this.updateCoinDisplay();
-
- // 初始化网格信息
- this.initGridInfo();
-
- // 初始化网格占用情况
- this.initGridOccupationMap();
-
- // 生成随机的三个块
- this.generateRandomBlocks();
- // 注册碰撞回调
- const collider = this.getComponent(Collider2D);
- if (collider) {
- collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- console.log('方块碰撞监听器已注册');
- }
- }
-
- // 确保有PlacedBlocks节点
- ensurePlacedBlocksNode() {
- // 查找Canvas节点
- const canvas = find('Canvas');
- if (!canvas) {
- console.error('找不到Canvas节点');
- return;
- }
-
- // 查找或创建PlacedBlocks节点
- let placedBlocksNode = find('Canvas/PlacedBlocks');
- if (!placedBlocksNode) {
- placedBlocksNode = new Node('PlacedBlocks');
- canvas.addChild(placedBlocksNode);
- // 确保PlacedBlocks节点有UITransform组件
- if (!placedBlocksNode.getComponent(UITransform)) {
- placedBlocksNode.addComponent(UITransform);
- }
- console.log('已创建PlacedBlocks节点');
- }
- }
-
- // 更新金币显示
- updateCoinDisplay() {
- if (this.coinLabelNode) {
- const label = this.coinLabelNode.getComponent(Label);
- if (label) {
- label.string = this.playerCoins.toString();
- }
- }
- }
-
- // 初始化网格信息
- initGridInfo() {
- if (!this.gridContainer || this.gridInitialized) return;
-
- // 创建二维数组存储网格节点
- this.gridNodes = [];
- for (let row = 0; row < this.GRID_ROWS; row++) {
- this.gridNodes[row] = [];
- }
-
- // 遍历所有网格节点,将它们放入二维数组
- for (let i = 0; i < this.gridContainer.children.length; i++) {
- const grid = this.gridContainer.children[i];
- if (grid.name.startsWith('Grid_')) {
- // 从节点名称解析行列信息,例如Grid_2_3表示第2行第3列
- const parts = grid.name.split('_');
- if (parts.length === 3) {
- const row = parseInt(parts[1]);
- const col = parseInt(parts[2]);
-
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- this.gridNodes[row][col] = grid;
- }
- }
- }
- }
-
- // 计算网格间距
- if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
- if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
- const pos1 = this.gridNodes[0][0].position;
- const pos2 = this.gridNodes[1][0].position;
- this.gridSpacing = Math.abs(pos2.y - pos1.y);
- }
- }
-
- this.gridInitialized = true;
- }
-
- // 初始化网格占用情况
- initGridOccupationMap() {
- this.gridOccupationMap = [];
- for (let row = 0; row < this.GRID_ROWS; row++) {
- const rowArray: number[] = [];
- for (let col = 0; col < this.GRID_COLS; col++) {
- rowArray.push(0);
- }
- this.gridOccupationMap.push(rowArray);
- }
- }
-
- generateRandomBlocks() {
- // 如果游戏已开始,只清除kuang区域的块,否则清除所有块
- this.clearBlocks();
-
- // 检查是否有预制体可用
- if (this.blockPrefabs.length === 0) {
- console.error('没有可用的预制体');
- return;
- }
-
- // 获取kuang节点
- const kuangNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
- if (!kuangNode) {
- console.error('找不到kuang节点');
- return;
- }
-
- // 位置偏移量
- const offsets = [
- new Vec3(-200, 0, 0),
- new Vec3(0, 0, 0),
- new Vec3(200, 0, 0)
- ];
-
- // 获取kuang节点下的db01、db02、db03节点
- const dbNodes = [
- kuangNode.getChildByName('db01'),
- kuangNode.getChildByName('db02'),
- kuangNode.getChildByName('db03')
- ];
-
- // 生成三个随机块
- for (let i = 0; i < 3; i++) {
- // 随机选择一个预制体
- const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
- const prefab = this.blockPrefabs[randomIndex];
-
- // 实例化预制体
- const block = instantiate(prefab);
- kuangNode.addChild(block); // 直接添加到kuang节点下
-
- // 设置位置
- block.position = offsets[i];
-
- // 保存原始位置
- this.originalPositions.set(block, offsets[i].clone());
-
- // 标记方块位置为kuang
- this.blockLocations.set(block, 'kuang');
-
- // 添加到块数组
- this.blocks.push(block);
-
- // 将对应的db节点与方块关联
- if (dbNodes[i]) {
- // 保存价格节点引用 (Price是db节点的子节点)
- const priceNode = dbNodes[i].getChildByName('Price');
- if (priceNode) {
- this.blockPriceMap.set(block, priceNode);
- priceNode.active = true;
- }
-
- // 将db节点作为方块的子节点
- this.associateDbNodeWithBlock(block, dbNodes[i]);
- }
-
- // 添加触摸事件
- this.setupDragEvents(block);
- }
- }
-
- // 将db节点与方块关联
- associateDbNodeWithBlock(block: Node, dbNode: Node) {
- // 记录db节点与方块的关联
- block['dbNode'] = dbNode;
-
- // 当方块移动时,db节点也跟随移动
- block.on(Node.EventType.TRANSFORM_CHANGED, () => {
- if (dbNode && block.parent) {
- // 检查方块当前位置
- const location = this.blockLocations.get(block);
-
- // 如果方块在网格中,不需要显示db节点
- if (location === 'grid') {
- dbNode.active = false;
- return;
- }
-
- // 确保db节点可见
- dbNode.active = true;
-
- // 获取方块在世界坐标系中的位置
- const worldPos = block.parent.getComponent(UITransform).convertToWorldSpaceAR(block.position);
-
- // 将世界坐标转换为db节点父节点的本地坐标
- const localPos = dbNode.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
-
- // 设置db节点位置,放在方块下方
- dbNode.position = new Vec3(localPos.x, localPos.y - 80, localPos.z);
- }
- });
- }
-
- // 获取方块价格
- getBlockPrice(block: Node): number {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- const label = priceNode.getComponent(Label);
- if (label) {
- // 尝试解析价格
- const price = parseInt(label.string);
- if (!isNaN(price)) {
- return price;
- }
- }
- }
- // 默认价格
- return 50;
- }
-
- // 隐藏价格标签
- hidePriceLabel(block: Node) {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- priceNode.active = false;
- }
- }
-
- // 显示价格标签
- showPriceLabel(block: Node) {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- priceNode.active = true;
- }
- }
-
- // 扣除玩家金币
- deductPlayerCoins(amount: number): boolean {
- if (this.playerCoins >= amount) {
- this.playerCoins -= amount;
- this.updateCoinDisplay();
- return true;
- }
- return false;
- }
-
- setupDragEvents(block: Node) {
- // 添加触摸开始事件
- block.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
- // 记录当前拖拽的块
- this.currentDragBlock = block;
- // 记录触摸起始位置
- this.startPos = event.getUILocation();
- // 记录块的起始位置
- this.blockStartPos.set(block.position);
- // 记录块的起始位置类型
- this.currentDragBlock['startLocation'] = this.blockLocations.get(block);
-
- // 将块置于顶层
- block.setSiblingIndex(block.parent.children.length - 1);
-
- // 临时保存方块占用的网格,而不是直接移除
- this.tempStoreBlockOccupiedGrids(block);
- }, this);
-
- // 添加触摸移动事件
- block.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
- if (!this.currentDragBlock) return;
-
- // 计算触摸点位移
- const location = event.getUILocation();
- const deltaX = location.x - this.startPos.x;
- const deltaY = location.y - this.startPos.y;
-
- // 更新块的位置
- this.currentDragBlock.position = new Vec3(
- this.blockStartPos.x + deltaX,
- this.blockStartPos.y + deltaY,
- this.blockStartPos.z
- );
- }, this);
-
- // 添加触摸结束事件
- block.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
- if (this.currentDragBlock) {
- // 获取当前触摸位置
- const touchPos = event.getUILocation();
- // 获取起始位置类型
- const startLocation = this.currentDragBlock['startLocation'];
-
- // 检查是否拖到了kuang区域
- if (this.isInKuangArea(touchPos)) {
- // 如果拖回kuang区域,恢复到原始位置
- const originalPos = this.originalPositions.get(this.currentDragBlock);
- if (originalPos) {
- // 确保方块在kuang节点下
- const kuangNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
- if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
- // 将方块从当前父节点移除
- this.currentDragBlock.removeFromParent();
- // 添加到kuang节点下
- kuangNode.addChild(this.currentDragBlock);
- }
-
- // 设置位置
- this.currentDragBlock.position = originalPos.clone();
- }
-
- // 恢复方块原来的占用状态(如果有)
- this.restoreBlockOccupiedGrids(this.currentDragBlock);
-
- // 更新方块位置标记
- this.blockLocations.set(this.currentDragBlock, 'kuang');
-
- // 确保价格标签显示
- this.showPriceLabel(this.currentDragBlock);
-
- // 如果方块之前在网格中,需要恢复金币
- if (startLocation === 'grid') {
- // 获取方块价格
- const price = this.getBlockPrice(this.currentDragBlock);
- // 恢复金币
- this.playerCoins += price;
- // 更新金币显示
- this.updateCoinDisplay();
- // 重置已放置标记
- this.currentDragBlock['placedBefore'] = false;
- }
-
- // 确保db节点可见并回到正确位置
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = true;
-
- // 触发一次位置更新,确保db节点位置正确
- this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
- }
- } else if (this.tryPlaceBlockToGrid(this.currentDragBlock)) {
- // 获取方块价格
- const price = this.getBlockPrice(this.currentDragBlock);
-
- // 如果方块之前在网格中,不需要重复扣除金币
- if (startLocation === 'grid') {
- // 清除临时保存的占用状态
- this.clearTempStoredOccupiedGrids(this.currentDragBlock);
-
- // 更新方块位置标记
- this.blockLocations.set(this.currentDragBlock, 'grid');
-
- // 隐藏价格标签
- this.hidePriceLabel(this.currentDragBlock);
-
- // 隐藏db节点
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = false;
- }
-
- // 如果游戏已经开始,将方块移动到PlacedBlocks节点下
- if (this.gameStarted) {
- this.moveBlockToPlacedBlocks(this.currentDragBlock);
- }
- } else {
- // 尝试扣除金币
- if (this.deductPlayerCoins(price)) {
- // 扣除成功,清除临时保存的占用状态
- this.clearTempStoredOccupiedGrids(this.currentDragBlock);
-
- // 更新方块位置标记
- this.blockLocations.set(this.currentDragBlock, 'grid');
-
- // 隐藏价格标签
- this.hidePriceLabel(this.currentDragBlock);
-
- // 隐藏db节点
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = false;
- }
-
- // 标记方块已经放置过
- this.currentDragBlock['placedBefore'] = true;
-
- // 如果游戏已经开始,将方块移动到PlacedBlocks节点下
- if (this.gameStarted) {
- this.moveBlockToPlacedBlocks(this.currentDragBlock);
- }
- } else {
- // 金币不足,放置失败,返回原位
- const originalPos = this.originalPositions.get(this.currentDragBlock);
- if (originalPos) {
- this.currentDragBlock.position = originalPos.clone();
- }
-
- // 恢复方块原来的占用状态
- this.restoreBlockOccupiedGrids(this.currentDragBlock);
-
- // 确保价格标签显示
- this.showPriceLabel(this.currentDragBlock);
-
- // 确保db节点可见并回到正确位置
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = true;
-
- // 触发一次位置更新,确保db节点位置正确
- this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
- }
- }
- }
- } else {
- // 放置失败,返回原位
- const currentLocation = this.blockLocations.get(this.currentDragBlock);
- if (currentLocation === 'kuang') {
- // 如果之前在kuang中,返回kuang中的位置
- const originalPos = this.originalPositions.get(this.currentDragBlock);
- if (originalPos) {
- this.currentDragBlock.position = originalPos.clone();
- }
- } else {
- // 否则返回拖拽开始的位置
- this.currentDragBlock.position = this.blockStartPos.clone();
- }
-
- // 恢复方块原来的占用状态
- this.restoreBlockOccupiedGrids(this.currentDragBlock);
-
- // 确保价格标签显示
- this.showPriceLabel(this.currentDragBlock);
-
- // 确保db节点可见并回到正确位置
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = true;
-
- // 触发一次位置更新,确保db节点位置正确
- this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
- }
- }
-
- this.currentDragBlock = null;
- }
- }, this);
-
- // 添加触摸取消事件
- block.on(Node.EventType.TOUCH_CANCEL, () => {
- if (this.currentDragBlock) {
- // 获取起始位置类型
- const startLocation = this.currentDragBlock['startLocation'];
-
- // 触摸取消,返回原位
- this.currentDragBlock.position = this.blockStartPos.clone();
-
- // 如果当前在kuang区域,确保方块在kuang节点下
- if (this.blockLocations.get(this.currentDragBlock) === 'kuang') {
- const kuangNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
- if (kuangNode && this.currentDragBlock.parent !== kuangNode) {
- // 将方块从当前父节点移除
- this.currentDragBlock.removeFromParent();
- // 添加到kuang节点下
- kuangNode.addChild(this.currentDragBlock);
- }
- }
-
- // 恢复方块原来的占用状态
- this.restoreBlockOccupiedGrids(this.currentDragBlock);
-
- // 确保价格标签显示
- this.showPriceLabel(this.currentDragBlock);
-
- // 如果方块之前在网格中且现在在kuang区域,需要恢复金币
- if (startLocation === 'grid' &&
- this.blockLocations.get(this.currentDragBlock) === 'kuang') {
- // 获取方块价格
- const price = this.getBlockPrice(this.currentDragBlock);
- // 恢复金币
- this.playerCoins += price;
- // 更新金币显示
- this.updateCoinDisplay();
- // 重置已放置标记
- this.currentDragBlock['placedBefore'] = false;
- }
-
- // 确保db节点可见并回到正确位置
- const dbNode = this.currentDragBlock['dbNode'];
- if (dbNode) {
- dbNode.active = true;
-
- // 触发一次位置更新,确保db节点位置正确
- this.currentDragBlock.emit(Node.EventType.TRANSFORM_CHANGED);
- }
-
- this.currentDragBlock = null;
- }
- }, this);
- }
-
- // 检查是否在kuang区域内
- isInKuangArea(touchPos: Vec2): boolean {
- if (!this.kuangContainer) return false;
-
- // 获取kuang的世界矩形
- const kuangTransform = this.kuangContainer.getComponent(UITransform);
- if (!kuangTransform) return false;
-
- // 计算kuang的世界边界
- const kuangBoundingBox = new Rect(
- this.kuangContainer.worldPosition.x - kuangTransform.width * kuangTransform.anchorX,
- this.kuangContainer.worldPosition.y - kuangTransform.height * kuangTransform.anchorY,
- kuangTransform.width,
- kuangTransform.height
- );
-
- // 检查触摸点是否在kuang矩形内
- return kuangBoundingBox.contains(new Vec2(touchPos.x, touchPos.y));
- }
-
- // 临时保存方块占用的网格
- tempStoreBlockOccupiedGrids(block: Node) {
- // 获取方块占用的网格
- const occupiedGrids = block['occupiedGrids'];
- if (!occupiedGrids || occupiedGrids.length === 0) return;
-
- // 保存到临时数组
- this.tempRemovedOccupiedGrids.push({
- block: block,
- occupiedGrids: [...occupiedGrids] // 复制一份,避免引用问题
- });
-
- // 移除占用标记
- for (const grid of occupiedGrids) {
- if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
- grid.col >= 0 && grid.col < this.GRID_COLS) {
- this.gridOccupationMap[grid.row][grid.col] = 0;
- }
- }
-
- // 清空方块的占用记录
- block['occupiedGrids'] = [];
- }
-
- // 恢复方块原来的占用状态
- restoreBlockOccupiedGrids(block: Node) {
- // 查找临时保存的占用状态
- const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
- if (index === -1) return;
-
- const savedItem = this.tempRemovedOccupiedGrids[index];
-
- // 恢复占用标记
- for (const grid of savedItem.occupiedGrids) {
- if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
- grid.col >= 0 && grid.col < this.GRID_COLS) {
- this.gridOccupationMap[grid.row][grid.col] = 1;
- }
- }
-
- // 恢复方块的占用记录
- block['occupiedGrids'] = [...savedItem.occupiedGrids];
-
- // 从临时数组中移除
- this.tempRemovedOccupiedGrids.splice(index, 1);
- }
-
- // 清除临时保存的占用状态
- clearTempStoredOccupiedGrids(block: Node) {
- // 查找临时保存的占用状态
- const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
- if (index === -1) return;
-
- // 从临时数组中移除
- this.tempRemovedOccupiedGrids.splice(index, 1);
- }
-
- // 获取网格行列索引
- getGridRowCol(gridNode: Node): { row: number, col: number } | null {
- if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
-
- const parts = gridNode.name.split('_');
- if (parts.length === 3) {
- const row = parseInt(parts[1]);
- const col = parseInt(parts[2]);
-
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- return { row, col };
- }
- }
-
- return null;
- }
-
- // 找到最近的网格节点
- findNearestGridNode(position: Vec3): Node {
- if (!this.gridContainer || !this.gridInitialized) return null;
-
- let nearestNode: Node = null;
- let minDistance = Number.MAX_VALUE;
-
- // 遍历所有网格节点
- for (let row = 0; row < this.GRID_ROWS; row++) {
- for (let col = 0; col < this.GRID_COLS; col++) {
- const grid = this.gridNodes[row][col];
- if (grid) {
- const distance = Vec3.distance(position, grid.position);
- if (distance < minDistance) {
- minDistance = distance;
- nearestNode = grid;
- }
- }
- }
- }
-
- // 增加容错性,放宽距离限制
- if (minDistance > this.gridSpacing * 2) {
- // 如果距离超过网格间距的4倍,可能是完全偏离了网格区域
- if (minDistance > this.gridSpacing * 4) {
- return null;
- }
- }
-
- return nearestNode;
- }
-
- // 尝试将方块放置到网格中
- tryPlaceBlockToGrid(block: Node): boolean {
- if (!this.gridContainer || !this.gridInitialized) return false;
-
- // 记录方块之前的位置
- const previousLocation = this.blockLocations.get(block);
-
- // 获取B1节点
- let b1Node = block;
- if (block.name !== 'B1') {
- // 查找B1节点
- b1Node = block.getChildByName('B1');
- if (!b1Node) {
- return false;
- }
- }
-
- // 获取方块B1节点在世界坐标中的位置
- const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
-
- // 将B1节点的世界坐标转换为GridContainer的本地坐标
- const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
-
- // 检查是否在GridContainer范围内
- const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
- const halfWidth = gridSize.width / 2;
- const halfHeight = gridSize.height / 2;
-
- // 增加容错性,放宽边界检查
- const tolerance = this.gridSpacing * 0.5;
- if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
- gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
- return false;
- }
-
- // 找到最近的网格节点
- const nearestGrid = this.findNearestGridNode(gridPos);
- if (!nearestGrid) {
- // 尝试使用网格行列直接定位
- const row = Math.floor((gridPos.y + halfHeight) / this.gridSpacing);
- const col = Math.floor((gridPos.x + halfWidth) / this.gridSpacing);
-
- // 检查计算出的行列是否在有效范围内
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- const grid = this.gridNodes[row][col];
- if (grid) {
- const result = this.tryPlaceBlockToSpecificGrid(block, grid);
-
- // 如果放置成功,处理db节点
- if (result) {
- const dbNode = block['dbNode'];
- if (dbNode) {
- // 隐藏db节点
- dbNode.active = false;
- }
-
- // 如果方块之前在网格中,不需要重复扣除金币
- if (previousLocation === 'grid') {
- block['placedBefore'] = true;
- }
- }
-
- return result;
- }
- }
-
- return false;
- }
-
- const result = this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
-
- // 如果放置成功,处理db节点
- if (result) {
- const dbNode = block['dbNode'];
- if (dbNode) {
- // 隐藏db节点
- dbNode.active = false;
- }
-
- // 如果方块之前在网格中,不需要重复扣除金币
- if (previousLocation === 'grid') {
- block['placedBefore'] = true;
- }
- }
-
- return result;
- }
-
- // 尝试将方块放置到指定的网格节点
- tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
- // 获取B1节点
- let b1Node = block;
- if (block.name !== 'B1') {
- b1Node = block.getChildByName('B1');
- if (!b1Node) {
- return false;
- }
- }
-
- // 检查方块的所有部分是否会与已占用的格子重叠
- if (!this.canPlaceBlockAt(block, targetGrid)) {
- return false;
- }
-
- // 获取网格节点的中心点世界坐标
- const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
-
- // 计算B1节点应该移动到的位置
- const targetWorldPos = gridCenterWorldPos.clone();
-
- // 计算根节点需要移动的位置
- // 1. 先计算B1节点相对于根节点的偏移
- const b1LocalPos = b1Node.position.clone();
-
- // 2. 计算根节点的目标世界坐标
- let rootTargetWorldPos;
- if (b1Node === block) {
- rootTargetWorldPos = targetWorldPos.clone();
- } else {
- // 如果B1是子节点,需要计算根节点应该在的位置,使B1对准网格中心
- rootTargetWorldPos = new Vec3(
- targetWorldPos.x - b1LocalPos.x,
- targetWorldPos.y - b1LocalPos.y,
- targetWorldPos.z
- );
- }
-
- // 3. 将世界坐标转换为根节点父节点的本地坐标
- const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
-
- // 设置方块位置,确保B1节点的中心与网格节点的中心对齐
- block.position = rootTargetLocalPos;
-
- // 标记占用的格子
- this.markOccupiedPositions(block, targetGrid);
-
- return true;
- }
-
- // 获取方块的所有部分节点及其相对坐标
- getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
- const parts: { node: Node, x: number, y: number }[] = [];
-
- // 添加B1节点本身(根节点)
- parts.push({ node: block, x: 0, y: 0 });
-
- // 递归查找所有子节点
- this.findBlockParts(block, parts, 0, 0);
-
- return parts;
- }
-
- // 递归查找方块的所有部分
- findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number) {
- // 遍历所有子节点
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
-
- // 跳过不参与占用的节点
- if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
- continue;
- }
-
- let x = parentX;
- let y = parentY;
-
- // 尝试从节点名称中解析坐标
- const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
- if (match) {
- // 如果节点名称是坐标格式,直接使用
- x = parseInt(match[1]);
- y = parseInt(match[2]);
- result.push({ node: child, x, y });
- } else if (child.name.startsWith('B')) {
- // 如果是B开头的节点,使用其相对位置
- // 计算相对于父节点的位置,并转换为网格单位
- const relativeX = Math.round(child.position.x / this.gridSpacing);
- const relativeY = -Math.round(child.position.y / this.gridSpacing); // Y轴向下为正
-
- x = parentX + relativeX;
- y = parentY + relativeY;
-
- result.push({ node: child, x, y });
- }
-
- // 递归处理子节点
- this.findBlockParts(child, result, x, y);
- }
- }
-
- // 检查方块是否可以放置在指定位置
- canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
- if (!this.gridInitialized) return false;
-
- // 获取目标网格的行列索引
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) return false;
-
- // 获取方块的所有部分
- const parts = this.getBlockParts(block);
-
- // 检查每个部分是否与已占用的格子重叠
- for (const part of parts) {
- // 计算在网格中的行列位置
- const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
- const col = targetRowCol.col + part.x; // X轴向右为正
-
- // 检查是否超出网格范围
- if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
- return false;
- }
-
- // 检查该位置是否已被占用
- if (this.gridOccupationMap[row][col] === 1) {
- return false;
- }
- }
-
- return true;
- }
-
- // 标记方块占用的格子
- markOccupiedPositions(block: Node, targetGrid: Node) {
- if (!this.gridInitialized) return;
-
- // 获取目标网格的行列索引
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) return;
-
- // 获取方块的所有部分
- const parts = this.getBlockParts(block);
-
- // 清除之前的占用记录
- block['occupiedGrids'] = [];
-
- // 为每个部分标记占用位置
- for (const part of parts) {
- // 计算在网格中的行列位置
- const row = targetRowCol.row - part.y; // Y轴向下为正,所以是减法
- const col = targetRowCol.col + part.x; // X轴向右为正
-
- // 检查是否在有效范围内
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- // 更新网格占用情况
- this.gridOccupationMap[row][col] = 1;
-
- // 存储方块与网格的关联
- block['occupiedGrids'] = block['occupiedGrids'] || [];
- block['occupiedGrids'].push({ row, col });
- }
- }
- }
-
- // 移除方块占用的格子
- removeBlockFromGrid(block: Node) {
- // 获取方块占用的网格
- const occupiedGrids = block['occupiedGrids'];
- if (!occupiedGrids) return;
-
- // 移除占用标记
- for (const grid of occupiedGrids) {
- if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
- grid.col >= 0 && grid.col < this.GRID_COLS) {
- this.gridOccupationMap[grid.row][grid.col] = 0;
- }
- }
-
- // 清空方块的占用记录
- block['occupiedGrids'] = [];
- }
-
- clearBlocks() {
- // 只移除kuang区域的块,保留已放置在网格中的块
- const blocksToRemove = [];
-
- // 找出所有在kuang区域的块
- for (const block of this.blocks) {
- if (block.isValid) {
- const location = this.blockLocations.get(block);
- if (location === 'kuang') {
- blocksToRemove.push(block);
- }
- }
- }
-
- // 移除kuang区域的块
- for (const block of blocksToRemove) {
- // 如果有关联的db节点,恢复其位置
- const dbNode = block['dbNode'];
- if (dbNode && dbNode.isValid) {
- // 移除方块移动时的监听
- block.off(Node.EventType.TRANSFORM_CHANGED);
-
- // 恢复db节点到原始位置
- const kuangNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
- if (kuangNode) {
- // 确保db节点回到原来的父节点下
- const dbName = dbNode.name;
- if (!kuangNode.getChildByName(dbName)) {
- dbNode.parent = kuangNode;
- }
- }
- }
-
- // 从blocks数组中移除
- const index = this.blocks.indexOf(block);
- if (index !== -1) {
- this.blocks.splice(index, 1);
- }
-
- // 清除相关映射
- this.originalPositions.delete(block);
- this.blockLocations.delete(block);
- this.blockPriceMap.delete(block);
-
- // 销毁方块
- block.destroy();
- }
-
- // 注意:不重置网格占用情况,保留已放置的方块占用信息
- }
-
- // 游戏开始时,确保已放置的方块正确显示
- onGameStart() {
- // 遍历所有方块
- for (const block of this.blocks) {
- if (block.isValid) {
- const location = this.blockLocations.get(block);
-
- // 如果方块在网格中,将其移动到PlacedBlocks节点下
- if (location === 'grid') {
- // 隐藏价格标签
- this.hidePriceLabel(block);
-
- // 隐藏db节点
- const dbNode = block['dbNode'];
- if (dbNode) {
- dbNode.active = false;
- }
-
- // 将方块移动到PlacedBlocks节点下
- this.moveBlockToPlacedBlocks(block);
- }
- }
- }
-
- // 设置游戏已开始标志
- this.gameStarted = true;
- }
-
- // 将方块移动到PlacedBlocks节点下
- moveBlockToPlacedBlocks(block: Node) {
- // 查找PlacedBlocks节点
- const placedBlocksNode = find('Canvas/PlacedBlocks');
- if (!placedBlocksNode) {
- console.error('找不到PlacedBlocks节点');
- return;
- }
-
- // 保存方块的世界位置
- const worldPosition = new Vec3();
- block.getWorldPosition(worldPosition);
-
- // 将方块从当前父节点移除
- block.removeFromParent();
-
- // 添加到PlacedBlocks节点下
- placedBlocksNode.addChild(block);
-
- // 设置方块的世界位置,确保在屏幕上的位置不变
- block.setWorldPosition(worldPosition);
-
- console.log(`已将方块 ${block.name} 移动到PlacedBlocks节点下`);
- }
- onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- console.log('方块碰到了:', otherCollider.node.name);
- // 如果碰到球,可以在这里发射子弹
- if (otherCollider.node.name === 'Ball') {
- console.log('方块被球击中!');
- // 这里可以调用发射子弹的逻辑
- }
- }
- }
|