美文网首页Unity+Code Learning
【Terrain x Perlin】用Perlin Noise

【Terrain x Perlin】用Perlin Noise

作者: zitaoye | 来源:发表于2019-08-04 00:47 被阅读0次

    GENERATING TERRAIN in Unity - Procedural Generation Tutorial

    比较老的视频,使用Terrain中设置perlinNoise来制作生成地形

    using UnityEngine;
    
    public class TerrainGenerator: MonoBehaviour {
      
      public int depth = 20;
      public int width = 256;
      public int height = 256;
    
      public float scale = 20;
      public float offsetX=100f;
      public float offsetY = 100f;
    
      void Start()
      {
        offsetX = Random.Range(0f,9999f);
        offsetY = Random.Range(0f,9999f);
      }
    
      //可以改成update用于测试
      void Update()
      {
        Terrain ter = GetComponent<Terrian>();
        ter.terrainData = GenerateTerrain(ter.terrainData);
    
        //可以有波纹
        offsetX += Time.deltaTime*5f;
      }
      
      TerrainData GenerateTerrain(TerrainData terrainData)
      {
        terrainData.heightmapResolution = width +1;
    
        terrainData.size = new Vector3(width, depth, height);
        terrainData.SetHeights(0,0,GenerateHeights());
        return terrainData;
      }
    
    
      float[,] GenerateHeights()
      {
        float[,] heights = new float[width,height];
        for (int x = 0; x<width; x++)
        {
          for(int y = 0; y <height; y ++)
            {
              heights[x,y] = CalculateHeight(x,y);
            }
        }
      return heights;
      }
    
      float CalculateHiegh(int x, int y )
      {
        //这边要记得转换float
        float xCoord = (float)x / width*scale+offsetX;
        float yCoord = (float)y / height*scale+offsetY;
    
        return Mathf.PerlinNoise(xCoord,yCoord);
      }
    
    }
    
    

    相关文章

      网友评论

        本文标题:【Terrain x Perlin】用Perlin Noise

        本文链接:https://www.haomeiwen.com/subject/wlxedctx.html