跳到主要内容

程序化关卡

此项目使用实体的 clone() 函数,根据编辑器中创建的实体随机生成关卡。

你可以在编辑器中打开教程项目进行尝试。

下面的脚本是一个非常简单的关卡生成程序。它将编辑器中设置好的 Grass 和 House 两个实体用作网格关卡的地块。生成关卡时,程序随机选择一个地块,将其克隆为新实体,再把新实体放到正确的网格位置。

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() {
// We've created a couple of templates that are our world tiles
// In the Editor hierarchy, we have disabled the templates because
// we don't want them to be visible. We just want our generated
// world to be visible
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++) {
// Pick a tile at random, with grass more likely than a house
var tile = (Math.random() > 0.8) ? house : grass;

// Clone the tile
var e = tile.clone();

// Set the world position of the cloned tile. Note that because
// our tiles are 10x10 in X,Z dimensions, we have to multiply
// the position by 10
e.setPosition((x - this.numTilesX / 2) * 10, 0, (y - this.numTilesX / 2) * 10);

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