Skip to content

Latest commit

 

History

History
96 lines (73 loc) · 2.47 KB

WorldGenerator.md

File metadata and controls

96 lines (73 loc) · 2.47 KB

WorldGenerator

WorldGenerator is used during the initialization process of a level (see level life cycle) to generate world objects in the level.

A WorldGenerator must implement a generate() method.

generate(world)

Create world objects

In the generate() method, you can use world.createObject() to create world objects.

Simple generator

This example creates a line of 10 Switch.

level.js:

module.exports = {
  // ...

  worldGenerator: {
    generate(world) {
      const xStart = 4
      const y = 4
      const switchCount = 10

      for (let x = xStart; x < xStart + switchCount; x++) {
        world.createObject('switch', {
          x: x,
          y: y,
          autoDisable: true
        })
      }
    }
  }
}

Advanced generator: dependent objects

This example creates 10 Switch, and 10 Spikes. We use the switches as triggers so that the spikes will get disabled when all switches are enabled.

Note: we make use of a Marker created in Tiled to generate all objects relative to its position. It's the intended way to use markers. It comes in very handy when the layout of the map is not definitive. That way you just have to move the Marker in Tiled and all these objects will move accordingly.

level.js:

module.exports = {
  // ...

  worldGenerator: {
    generate(world) {
      // Find the marker created with Tiled. We know that its id is 12 from Tiled.
      const marker = world.findObjectByID(12)
      const objectLineLength = 10

      // Create switches and store their ids in switchIds for later use.
      let switchIds = []

      for (let x = marker.x; x < marker.x + objectLineLength; x++) {
        let id = world.createObject('switch', {
          x: x,
          y: marker.y,
          autoDisable: true
        })

        switchIds.push(id)
      }

      // Create the spikes.
      const triggers = switchIds.join(',')

      for (let x = marker.x; x < marker.x + objectLineLength; x++) {
        world.createObject('spikes', {
          x: x,
          y: marker.y + 1,
          enabled: true,
          triggers: triggers
        })
      }
    }
  }
}