从perlin噪音创建地形

时间:2015-06-28 19:51:08

标签: unity3d unityscript noise perlin-noise

所以我一直在尝试制作类似Minecraft的无限动态世界一代,并且一直在使用Perlin Noise来获得随机但平滑的地形。我现在使用Unity(版本5.0.2f1),所以请原谅任何非纯JavaScript的东西。

(为了安全起见,我提醒那些不熟悉Unity游戏引擎的人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
}

1 个答案:

答案 0 :(得分:1)

您不应该使用Unity的构造函数,因为Unity本身将创建实例,然后调用Start()函数。使用Start()和Awake()来执行通常在构造函数中执行的操作(比如调用terrain生成函数)。我也强烈建议你选择c#。

所以我的方法是,在你的脚本附加到的GameObject的检查器中设置x,y,z和size。然后在Start()中调用Generate()函数。