Skip to main content

Procedural Levels

This project uses clone() function on the Entity to randomly generate a level from Entities that have been created in the Editor.

Try it from the Editor in the tutorial project.

This script below is a very simple level generation program. It takes two Entities that have been setup in the Editor: 'Grass' and 'House' and uses them as tiles for a grid based level. The level is created by randomly choosing one of the tiles, cloning the tile to create a new Entity, then placing the new Entity at the correct grid position.

import { Script } from 'playcanvas';

/**
* Generate dynamically spawns a grid of tiles using predefined templates.
* Tiles are randomly chosen between grass and house, with grass being more frequent.
*/
export class Generate extends Script {
static scriptName = 'generate';

/**
* Number of tiles to spawn along the X-axis.
*
* @attribute
* @type {number}
*/
numTilesX = 10;

/**
* Number of tiles to spawn along the Y-axis.
*
* @attribute
* @type {number}
*/
numTilesY = 10;

initialize() {
// Reference to the template group in the hierarchy
const templates = this.app.root.findByName('Templates');
const grass = templates.findByName('Grass');
const house = templates.findByName('House');

for (let y = 0; y < this.numTilesY; y++) {
for (let x = 0; x < this.numTilesX; x++) {
// Pick a tile at random (80% grass, 20% house)
const tile = Math.random() > 0.8 ? house : grass;

// Clone the selected template
const e = tile.clone();

// Position tiles in a 10x10 grid
const posX = (x - this.numTilesX / 2) * 10;
const posZ = (y - this.numTilesY / 2) * 10;
e.setPosition(posX, 0, posZ);

// Add the tile to the scene hierarchy
this.app.root.addChild(e);
}
}
}
}