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

Vue中使用Pixi.js实现六边形地图时点击六边形报错的问题

问题解决思路

一、修复六边形点击事件报错

你当前的报错核心原因是**hitArea的坐标体系错误**:
Pixi.js中,hitArea的坐标是相对于元素自身的局部坐标系,而非全局舞台坐标。你给hex设置了hex.x = hexCenter.x和hex.y = hexCenter.y来定位,但hitArea用的hexPoints是全局坐标,导致碰撞检测区域和实际绘制的六边形完全错位,触发鼠标事件时引发内部计算错误。

修正代码

把hexPoints转换为六边形自身的局部坐标(每个点减去中心坐标),再用来绘制和设置hitArea:

const hex = new PIXI.Graphics();
// 计算局部坐标:原始点减去六边形中心坐标,得到相对于hex自身的位置
const localHexPoints = hexPoints.map(p => new PIXI.Point(p.x - hexCenter.x, p.y - hexCenter.y));

hex.beginFill(0xffffff, 1);
hex.lineStyle(2.5, 0xffffff, 1);
// 用局部坐标绘制多边形
hex.drawPolygon(localHexPoints);
hex.x = hexCenter.x;
hex.y = hexCenter.y;

hex.eventMode = "dynamic";
// hitArea使用局部坐标的多边形,确保碰撞区域和视觉区域一致
hex.hitArea = new PIXI.Polygon(localHexPoints);
hex.on("click", handleClick);

function handleClick() {
  console.log(`Clicked on hexagon at grid coordinates (${coord.x}, ${coord.y})`);
  hex.off("click", handleClick);
  app.stage.removeChild(hex);
}
app.stage.addChild(hex);

二、应用级点击的坐标转换方案

如果要在全局绑定点击事件,需要把屏幕坐标转换为地图容器的局部坐标,再计算网格位置:

  1. 先给地图创建独立容器(管理所有六边形,方便坐标转换):
const mapContainer = new PIXI.Container();
app.stage.addChild(mapContainer);
// 所有六边形都添加到mapContainer中,而不是直接加到stage
mapContainer.addChild(hex);
  1. 绑定全局点击事件并转换坐标:
app.stage.on("click", (event) => {
  // 获取鼠标的全局舞台坐标
  const globalPos = event.data.global;
  // 转换为mapContainer的局部坐标(自动抵消容器的位移、缩放等变换)
  const localPos = mapContainer.toLocal(globalPos);
  
  // 这里根据你的六边形网格规则,用localPos计算对应的网格坐标(coord.x, coord.y)
  // 示例逻辑(需根据你的六边形布局调整):
  // const hexWidth = 你的六边形宽度;
  // const hexHeight = 你的六边形高度;
  // const gridX = Math.floor(localPos.x / hexWidth);
  // const gridY = Math.floor(localPos.y / hexHeight);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:43