用户:
一个STUB用户_6715468查看:3 回复:5 评论:3 创建时间:2021-07-24T13:01:57
我们看到社区里有很多地形生成器的代码
但代码普遍很长,并且看不懂
这次来教大家自己做一个山峰生成器
首先要学会造圆,具体看https://shequ.codemao.cn/community/382060
然后复制其中造圆(不是球)的函数:
function circle(radius, position, voxel) {
for (let x = position.x - radius; x <= position.x + radius; x++) {
for (let z = position.z - radius; z <= position.z + radius; z++) {
if (new Box3Vector3(x, position.y, z).distance(position) <= radius){
voxels.setVoxel(x, position.y, z, voxel);
}
}
}
}
由于山峰都不是规则性的,我们要加入一个参数,叫“outerIntegrity”(外层完整性),默认值为1,接下来把函数改成这样:
function circle(radius, position, voxel, outerIntegrity = 1) {
for (let x = position.x - radius; x <= position.x + radius; x++) {
for (let z = position.z - radius; z <= position.z + radius; z++) {
if (new Box3Vector3(x, position.y, z).distance(position) + 1 < radius) {
voxels.setVoxel(x, position.y, z, voxel);
} else if (new Box3Vector3(x, position.y, z).distance(position) < radius) {
if (Math.random() <= outerIntegrity && voxels.getVoxelId(x, position.y-1, z) != 0) {
voxels.setVoxel(x, position.y, z, voxel);
}
}
}
}
}
调用这个函数,outerIntegrity设为0.1到0.9之间的任何一个数,生成了一个不完整的圆
但怎么造山峰呢?现在我们用不完整的圆造山峰
一层一层地堆起来就是一个山峰了
接下来我们来定义一个函数,叫“generateMountain”,写写里面的代码:
function generateMountain(maxHigh, position, maxRadius, voxel) {
var radius = maxRadius;
var current = 0;
var high = 0;
for (let y = position.y; y <= position.y + maxHigh; y++) {
circle(radius,position.add(new Box3Vector3(0,high,0)),voxel,1 / (y - current));
high ++;
if(y % Math.floor(maxHigh / radius) == 0){
current = y;
radius --;
}
}
}
是不是简单易懂?
相信聪明人已经明白了地形生成器怎么做,我就不说了
完整代码:
function circle(radius, position, voxel, outerIntegrity = 1) {
for (let x = position.x - radius; x <= position.x + radius; x++) {
for (let z = position.z - radius; z <= position.z + radius; z++) {
if (new Box3Vector3(x, position.y, z).distance(position) + 1 < radius) {
voxels.setVoxel(x, position.y, z, voxel);
} else if (new Box3Vector3(x, position.y, z).distance(position) < radius) {
if (Math.random() <= outerIntegrity && voxels.getVoxelId(x, position.y-1, z) != 0) {
voxels.setVoxel(x, position.y, z, voxel);
}
}
}
}
}
function generateMountain(maxHigh, position, maxRadius, minRadius, voxel) {
var radius = maxRadius;
var current = 0;
var high = 0;
for (let y = position.y; y <= position.y + maxHigh; y++) {
circle(radius,position.add(new Box3Vector3(0,high,0)),voxel,1 / (y - current));
high ++;
if(y % Math.floor(maxHigh / maxRadius) == 0){
current = y;
radius --;
}
}
}
//调用:
generateMountain(喵,new Box3Vector3(喵,9,喵),16,8,'stone');
好了,本次教程就到这里,猜猜下次出什么呢?