所以我一直在尝试制作一个类似Minecraft的无限动态世界生成,并一直在使用Perlin Noise来获得随机但平滑的地形。我现在使用的是Unity(5.0.2f1版本),所以请原谅任何非纯JavaScript的东西。
(为了安全起见,我要提醒那些不熟悉Unity Game Engine的人,Start()
被称为第一帧,yield;
告诉引擎在不等待完成的情况下继续下一帧。)
实际情况是Start()
函数和构造函数都可以工作,但构造函数未能调用GenerateFloor()
。
感谢您的帮助。从现在开始谢谢。
代码(UnityScript):
#pragma strict
/*
This creates only one chunk so it should be called once for each chunk to be generated
*/
var size = 256; //"Blocks" in a chunk, note that a chunk has to be a square prism because the size is square rooted to generate each side.
var x : float;
var y : float;
var z : float;
var currentX : float;//Note : The first block in the
var currentZ : float;//chunk is (0, 0) and not (1, 1).
public var seed : int;
var heightMap : Vector3[];
print(Mathf.PerlinNoise(currentX, currentZ));
function Start(){
TerrainGenerator(new Vector3(10, 20, 30));
print("Start() is working"); //For debug
}
function TerrainGenerator(coords : Vector3){
x = coords.x;
y = coords.y;
z = coords.z;
print("Constructor worked.");//For debug
}
function Generate(){
GenerateFloor();
GenerateCaves();
}
function GenerateFloor(){
print("GenerateFloor() was called");//For debug
if(!(seed > 0)){
Debug.LogError("Seed not valid. Seed: " + seed + " .");
seed = Random.Range(0, 1000000000000000);
Debug.LogError("Generated new seed. Seed: " + seed + ".");
}
for(var i = 0; i < heightMap.length; i++){
if(currentX == Math.Sqrt(size)){
currentX = 0;
currentZ++;
}
else if(currentX > Math.Sqrt(size)) Debug.LogError("How did this happen?! currentX = " + currentX + " size = " + size + " .");
var height = Mathf.PerlinNoise(currentX, currentZ);
heightMap[currentX * currentZ] = new Vector3(currentX, height, currentZ);
print("For loop worked");//For debug
yield;
}
}
function GenerateCaves(){
//Coming soon
}
您不应该使用带有Unity的构造函数,因为Unity本身将创建实例,然后调用Start()函数。使用Start()和Awake()执行通常在构造函数中执行的操作(例如调用地形生成函数)。我还强烈建议你选择c#。
因此,我的方法是,在脚本所附的GameObject的检查器中设置x、y、z和size。然后在Start()中调用Generate()函数。