有没有办法在一个关卡中合并多个图块 - Kaboom JS

Is there a way to merge multiple tiles in a level - Kaboom JS

当在 kaboomJS 中制作具有大型瓦片地图碰撞的关卡时,事情开始变得缓慢...所以我想知道是否有一种简单的方法来合并多个瓦片,比如可以处理整行块作为一大块?

1。瓷砖不必适合网格

如果您想一次减少场景中游戏对象的数量,您可以在关卡定义中使用单个符号来表示跨越多个网格图块的游戏对象。所以如果你想要很多 3 个方格宽的平台,你不需要每个平台 3 个对象,你可以只用一个字符来表示一个 3x1 的矩形:

import kaboom from "kaboom"

// initialize context
kaboom()

// load assets
loadSprite("bean", "sprites/bean.png")

addLevel(
  // Note: the hyphens here hare just place holders to remind us that the
  // game objects created by ➁ and ➂ are actually taking up 2 and 3 grid
  // squares respectively.
  [
    "    ⚥                           ",
    "                                ",
    "            ➂--                 ",
    "                                ",
    "       ➁-                       ",
    "                                ",
    "                                ",
    "################################",
  ],
  {
    width: 32,
    height: 32,
    "⚥": () => [
        sprite("bean"),
        area(),
      body(),
      "player"
    ],
    "#": () => [
      rect(32, 32),
      outline(2),
      area(),
      solid(),
    ],
    "➁": () => [
      rect(32 * 2, 32),
      outline(2),
      area(),
      solid(),
    ],
    "➂": () => [
      rect(32 * 3, 32),
      outline(2),
      area(),
      solid(),
    ],
  }
);

const player = get("player")[0];

player.onUpdate(() => {
  const left = isKeyDown('left') || isKeyDown('a');
  const right = isKeyDown('right') || isKeyDown('d');
  if (left && !right) {
    player.move(-500, 0);
  } else if (right && !left) {
    player.move(500, 0);
  }
  camPos(player.pos);
});

onKeyPress("space", () => {
  if (player.isGrounded()) {
    player.jump();
  }
});

显然,如果您有许多不同的形状和大小,这将非常繁琐。

2。高级:四叉树和 Loading/Unloading 区域

我实际上 运行 在最近的一个 Kaboom 项目中遇到了这个问题,并决定用我自己的实现彻底改造内置 addLevel() 从位图而不是一堆字符串加载,然后将关卡数据组织成 quadtree so that I could quickly find chunks that overlapped the visible area, and load and unload game objects based on their visibility. The technique and code are a bit to complex it include here, so I'll just link to the Repl and the relevant source code: level-loader.ts and lib-quad-tree.ts and the usage in level-one.js .