矿石的随机生成
右键 创建节点=》创建空节点;新建一个区域,用于生成矿石,按快捷键T调整到如图大小
开始编写代码,新建Game.ts文件
在onLoad里写代码
你可以在这个图集里找到各种素材
从图集哩的素材生成预制体
把Game.ts挂载到上面创建的itemArea,并在onLoad上方添加代码
@property([cc.Prefab])
itemPrefabs: cc.Prefab[] = []
调整预制体数组大小,将预制体拖入
继续补充generateItems方法
Game.ts
/**
* 生成矿石
*/
generateItems() {
let that = this;
cc.loader.loadRes('MineItems', function (err, jsonAsset) {
that.generateList = [{ "name": "gold-0-0", "count": 1 }, { "name": "diamond", "count": 1 }, { "name": "TNT", "count": 1 },
{ "name": "gold-0-5", "count": 1 }, { "name": "stone-0", "count": 1 }]
//每种矿石依次生成
that.generateList.forEach(function (v) {
for (let i = 1; i <= v.count; i++) {
let tmp = cc.instantiate(that.prefabsByName[v.name]);
tmp.parent = that.node;
let pos = that.randomXY(); //生成随机位置
tmp.setPosition(pos);
}
})
});
}
/**
* 随机坐标
*/
randomXY() {
let randX = this.randomNum(30, this.node.width - 100);
let randY = this.randomNum(30, this.node.height - 100);
return cc.v2(randX, randY);
}
运行游戏,矿石可以随机生成了