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

Phaser中Tile组拖拽实现方案咨询及容器拖拽失效排查

问题描述

我有一组Tile,想把它们设置成可拖拽状态。知道直接移动Group或其子对象不可行,想找除了给每个Tile单独声明变量之外的替代方案。

更新:我尝试用Container实现,但控制台没报错却拖不动,代码如下:

this.grass = this.add.image(200, 100, "tileTexture", 0);
this.dirt = this.add.image(200, 116, "tileTexture", 1);

this.container = this.add.container(0, 0, [ this.grass, this.dirt ]);
this.container.setSize(this.grass.width,(this.grass.height*2))
this.container.setInteractive();
this.input.setDraggable(this.container);

this.input.on("drag", function (pointer, gameObject, dragX, dragY) {
  gameObject.x = dragX;
  gameObject.y = dragY;
});
解决办法

你的问题出在拖拽时的坐标赋值逻辑上。dragX和dragY是指针当前的绝对位置,但Container默认锚点为(0,0),直接将这两个值赋给容器的x、y,会导致容器左上角直接跳到指针位置,出现偏移甚至拖拽失效的错觉。

正确的做法是在拖拽开始时记录指针相对于容器的偏移量,拖拽过程中用指针位置减去该偏移量来设置容器坐标:

this.grass = this.add.image(200, 100, "tileTexture", 0);
this.dirt = this.add.image(200, 116, "tileTexture", 1);

this.container = this.add.container(0, 0, [this.grass, this.dirt]);
this.container.setSize(this.grass.width, this.grass.height * 2);
this.container.setInteractive();
this.input.setDraggable(this.container);

// 记录拖拽开始时指针与容器的偏移量
let dragOffsetX, dragOffsetY;

this.input.on("dragstart", function (pointer, gameObject) {
  dragOffsetX = pointer.x - gameObject.x;
  dragOffsetY = pointer.y - gameObject.y;
});

this.input.on("drag", function (pointer, gameObject, dragX, dragY) {
  // 用指针当前位置减去偏移量,保证拖拽手感符合预期
  gameObject.x = dragX - dragOffsetX;
  gameObject.y = dragY - dragOffsetY;
});

另外补充一个优化点:你创建Container时初始位置设为(0,0),但内部图片用的是绝对坐标,这会导致容器位置和Tile视觉位置脱节。更合理的方式是将Container初始位置设为Tile的基准位置,内部图片相对容器定位:

// 容器初始位置设为grass的绝对位置
this.container = this.add.container(200, 100);
// grass相对容器坐标为(0,0),直接添加即可
this.container.add(this.grass);
// dirt相对容器的y轴偏移16,设置相对位置
this.dirt.setPosition(0, 16);
this.container.add(this.dirt);

这样容器位置和Tile视觉位置完全对齐,拖拽操作会更符合直觉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:12:11