melonJS
    Preparing search index...

    Function mergeGridRects

    • Cover the cells of a grid that pass a test with as few rectangles as a simple sweep gives: each row's runs of cells, a run joined to the one right above it when both span the same columns. A wall of a thousand solid tiles becomes one rectangle rather than a thousand, which is what a physics world wants for the static bodies of a level, and no cell is covered twice.

      Parameters

      • cols: number

        the grid's width, in cells

      • rows: number

        the grid's height, in cells

      • test: (col: number, row: number) => boolean

        true for a cell to cover

      Returns { height: number; width: number; x: number; y: number }[]

      the rectangles, in cells

      // one static body per run of solid tiles of a layer
      const { tilewidth, tileheight } = layer;
      for (const r of me.mergeGridRects(layer.cols, layer.rows, (c, r) => layer.cellAt(c, r) !== null)) {
      const wall = new me.Renderable(r.x * tilewidth, r.y * tileheight, r.width * tilewidth, r.height * tileheight);
      wall.anchorPoint.set(0, 0);
      wall.bodyDef = {
      type: "static",
      shapes: [new me.Rect(0, 0, wall.width, wall.height)],
      collisionType: me.collision.types.WORLD_SHAPE,
      };
      app.world.addChild(wall);
      }