flauwekeul / honeycomb

Create hex grids easily, in node or the browser.
https://abbekeultjes.nl/honeycomb
MIT License
639 stars 59 forks source link

How do I loop through every hex of my grid (especially the first) ? #81

Closed MonsieurBibo closed 2 years ago

MonsieurBibo commented 2 years ago

Hello, foremost, thank you, @flauwekeul for this library, even if the TS rewrite isn't done it is already looking great. I needed to interact with hexagons in JS, and your package seems the best available on NPM.

However, I'm facing a problem. I'm trying to display a grid of hexes with the help of PIXI.JS. However, when doing so, the first hex isn't going through the each method (it is normal by default). That causes me an issue as I want to fill every hexagon on my grid. I tried using the start: [0,0] but it didn't work.

I thought of a hacky solution: create a line of x+1 elements and offsetting it of 1 to the left, then create a rectangle with y-1 rows. That works, but I need to modify a bit my data in order to have that first “invisible” element.

How could I write this properly ?

Thanks in advance.

P.S. I'm using 4.0.0-alpha.5

flauwekeul commented 2 years ago

Hi. Can you show some code? It should work 😕

MonsieurBibo commented 2 years ago

No problem.

I'm using :

 "svelte": "^3.44.0",
 "typescript": "^4.5.4",
 "vite": "^2.9.9",
 "honeycomb-grid": "4.0.0-alpha.5",
 "pixi.js": "^6.3.2"

Here is a simpler version of my code :


  import * as PIXI from "pixi.js";
  import {
    createHexPrototype,
    Grid,
    Hex,
    rectangle,
  } from "honeycomb-grid";

  (async () => {

    const div = document.querySelector("#app");
    const app = new PIXI.Application({
      resizeTo: div as HTMLElement, 
      backgroundAlpha: 0,
      antialias: true,
      autoDensity: true,
      resolution: 3,
    });
    const graphics = new PIXI.Graphics();
    if (div.children.length == 0) {
      div.appendChild(app.view);
    }

    graphics.lineStyle({ width: 1});

    const hexPrototype = createHexPrototype({
      dimensions: 12,
      origin: "topLeft",
    });

    const grid = new Grid(
      hexPrototype,
      rectangle({ start: [0, 0], width: 5, height: 5 })
    )
      .each((hex) => {
        let polygon = new PIXI.Polygon(
          { x: hex.corners[0].x, y: hex.corners[0].y },
          { x: hex.corners[1].x, y: hex.corners[1].y },
          { x: hex.corners[2].x, y: hex.corners[2].y },
          { x: hex.corners[3].x, y: hex.corners[3].y },
          { x: hex.corners[4].x, y: hex.corners[4].y },
          { x: hex.corners[5].x, y: hex.corners[5].y }
        ); // 🤮

        graphics.drawPolygon(polygon).beginFill(0xff3ff3f); // red
        app.stage.addChild(graphics);
      })
      .run();
  })();

Here is the result :

image

MonsieurBibo commented 2 years ago

Well, I tried to use SVG.js instead, and it worked ! I have now much better performances and no issue with the first tile