You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Phaser 3中销毁Tiled地图瓦片?

Phaser 3 瓦片销毁实现方案

核心思路

别用tile.destroy(),Phaser 3里移除瓦片得用图层自带的方法,直接操作tile对象容易出图层相关报错,正确姿势是用removeTileAt()或者removeTileAtWorldXY()。

具体操作步骤

1. 先拿到可编辑的动态图层

首先得确保你用的是动态图层(DynamicTilemapLayer),静态图层没法修改。初始化地图的时候这么写:

// 加载地图和 tileset 后
const map = this.make.tilemap({ key: '你的地图key' });
const tileset = map.addTilesetImage('Tiled里的tileset名', '对应纹理的key');
// 重点:createDynamicLayer 才是可编辑的
const groundLayer = map.createDynamicLayer('Tiled里的图层名', tileset, 0, 0);

2. 两种移除瓦片的方法

  • 按网格坐标删:知道瓦片在地图里的x、y网格位置的话,直接调用:
    // 第三个参数传true,会自动更新碰撞面,避免玩家穿模
    groundLayer.removeTileAt(5, 5, true);
    
  • 按鼠标点击的世界坐标删:如果是玩家点击破坏,先把屏幕坐标转成网格坐标再删:
    this.input.on('pointerdown', (pointer) => {
      // 把鼠标坐标转成世界坐标
      const worldPos = pointer.positionToCamera(this.cameras.main);
      // 再转成地图的网格坐标
      const tileCoords = groundLayer.worldToTileXY(worldPos.x, worldPos.y);
      
      // 确保坐标有效(不在地图外)
      if (tileCoords.x >= 0 && tileCoords.y >= 0) {
        groundLayer.removeTileAt(tileCoords.x, tileCoords.y, true);
      }
    });
    

3. 解决你遇到的图层报错

  • 检查图层名称:你代码里写的图层名要和Tiled里的完全一致,大小写都不能错
  • 确认是动态图层:如果用了createStaticLayer,那肯定改不了,必须换成createDynamicLayer
  • 别直接操作tile对象:tile.destroy()不是官方推荐的移除方式,容易搞乱图层的数据结构,就用上面说的图层方法

额外优化(可选)

要做Terraria那种破坏效果的话,删瓦片的时候可以加个粒子动画:

this.input.on('pointerdown', (pointer) => {
  const worldPos = pointer.positionToCamera(this.cameras.main);
  const tileCoords = groundLayer.worldToTileXY(worldPos.x, worldPos.y);
  
  if (tileCoords.x >= 0 && tileCoords.y >= 0) {
    const tile = groundLayer.getTileAt(tileCoords.x, tileCoords.y);
    if (tile) {
      // 在瓦片中心生成粒子
      this.add.particles(tile.getCenterX(), tile.getCenterY(), 'particle-texture', {
        speed: 120,
        lifespan: 600,
        scale: { start: 1.2, end: 0 }
      });
      groundLayer.removeTileAt(tileCoords.x, tileCoords.y, true);
    }
  }
});

内容的提问来源于stack exchange,提问作者Vatsa Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:30:59