プログラムでのステージの生成
このプロジェクトでは、エディターで作成されたエンティティを元に、clone() 関数を使用してステージ(レベル)をランダムに生成しています。
チュートリアルプロジェクトのエディターからお試しください。
以下のスクリプトは非常にシンプルなステージ(レベル)生成プログラムです。エディタで設定された2つのエンティティ、「Grass(草)」と「House(家)」をタイルとして使用し、グリッドベースのレベルを作成します。レベルは、タイルの中からランダムに1つ選択し、そのタイルを複製して新しいエンティティを作成し、新しいエンティティを正しいグリッド位置に配置することで作成されます。
- ESM
- Classic
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);
}
}
}
}
var Generate = pc.createScript('generate');
Generate.attributes.add('numTilesX', {
type: 'number',
default: 10
});
Generate.attributes.add('numTilesY', {
type: 'number',
default: 10
});
// initialize code called once per entity
Generate.prototype.initialize = function() {
// ワールドタイルとして使用する2つのテンプレートを作成しました
// エディタの階層構造では、テンプレートを非表示にしておきます。
// 私たちが生成したワールドは表示したくないからです。
var templates = this.app.root.findByName('Templates');
var grass = templates.findByName('Grass');
var house = templates.findByName('House');
for (var y = 0; y < this.numTilesY; y++) {
for (var x = 0; x < this.numTilesX; x++) {
// 草より家の方が大きい確率でタイルを選択
var tile = (Math.random() > 0.8) ? house : grass;
// タイルをクローン
var e = tile.clone();
// クローンされたタイルのワールド座標を設定します。
// テンプレートのサイズが X 増後に 10x10 であるため、座標を 10 倍する必要があることに注意してください。
e.setPosition((x - this.numTilesX / 2) * 10, 0, (y - this.numTilesX / 2) * 10);
// シーンの階層にタイルを追加します。
this.app.root.addChild(e);
}
}
};