为什么Unity卡在Application.EnterPlayMode上?

3

我正在尝试使用Perlin噪声和Marching Cubes在Unity中创建程序化地形生成器。在我从创建高度图转换为将其转换为3D数组后,它就无法工作了。每当我点击播放时,Unity都会打开一个带有Application.EnterPlayMode的对话框,并且不会进入播放模式。发生这种情况时,所有内容都停止响应,唯一停止它的方法是在任务管理器中终止它。

涉及的脚本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Noise : MonoBehaviour
{
    //Determines whether to show debug values
    public bool debug = false;

    //Determines flatness of the terrain
    public float noiseScale = 0.5f;

    //Type of perlin noise to use
    public enum PerlinNoise {
        twoD,
        threeD
    };
    public PerlinNoise perlinNoiseDimension = PerlinNoise.twoD;

    //To return noise data after all calculations
    public float[,,] getTerrainData(int x, int y, int z)
    {
        float[,,] terrainData = new float[x, y, z];

        if(perlinNoiseDimension == PerlinNoise.twoD)
        {
            terrainData = PerlinNoise2D(x, y, z, noiseScale);
        }
        return terrainData;
    }

    //Determine noise values using 2D Perlin noise
    private float[,,] PerlinNoise2D(int x, int y, int z, float noiseScale)
    {
        float[,,] voxelHeights = new float[x, y, z];

        if (debug)
        {
            Debug.Log("Heightmap");
        }

        //Origin points to sample from
        float xOrg = Random.Range(0.0f, 0.9999999f);
        float yOrg = Random.Range(0.0f, 0.9999999f);

        for (int currentx = 0; currentx < x; currentx++)
        {
            for (int currenty = 0; currenty < y; currenty++)
            {
                //Convert Values to Fractions
                float xCoord = (float)currentx / (x * noiseScale) + xOrg;
                float yCoord = (float)currenty / (y * noiseScale) + yOrg;

                float height = Mathf.PerlinNoise(xCoord, yCoord) * z;

                for(int currentz = 0; currentz <= height; z++)
                {
                    voxelHeights[currentx, currenty, currentz] = 1;
                }

                if (debug)
                {
                    Debug.Log("Height = " + height + ", X = " + currentx + ", Y = " + currenty + ", X Coord = " + xCoord + ", Y Coord = " + yCoord);
                }
            }

        }
        return voxelHeights;
    }
}

下面是它显示的图像: The error

derHugo的答案对我来说看起来相当正确。 我会补充说明,我不建议使用Unity的Mathf.PerlinNoise功能。Perlin可能是标志性的噪声名称,但它会产生可见的网格对齐,并且现在可能很少是最佳选择。 我会寻找良好的Simplex噪声实现进行导入。这样你的山脉就不会都对齐45度和90度了。 - KdotJPG
1个回答

6

你正在导致一个无限循环

for(int currentz = 0; currentz <= height; z++)
{
    voxelHeights[currentx, currenty, currentz] = 1;
}

在这里,你增加了z++,但是你的循环条件是currentz <= height。在循环内部,你从未更新currentz的值或者height的值,因此你的循环永远无法结束。

由于使用了索引,应该更改为:

for(int currentz = 0; currentz <= height; currentz++)
{
    voxelHeights[currentx, currenty, currentz] = 1;
}

不过我不确定这里的`height`如何起作用,因为我预期它应该看起来有点像这样。
for(int currentz = 0; currentz < z; currentz++)
{
    voxelHeights[currentx, currenty, currentz] = height;
}

我觉得这更有意义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接