生成随机地形

作者:追风剑情 发布于:2018-12-15 18:36 分类:Unity3d

示例代码

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using UnityEngine;
using UnityEditor;

// 测试: 随机生成高度图
public class TestHeightmap : MonoBehaviour {
	//高度图分辨率
	//对应 Heightmap Resolution = 65 (顶点数)
	public int width = 64;
	public int heiht = 64;
	//柏林噪声参数
	public float xOrg = 0F;
    public float yOrg = 0F;
	public float scale = 12.0F;
	public Texture2D noiseTexture;
	//地形
	public Terrain terrain;
	//地形高度数据,数组中的值即为对应顶点的高度值
	public float[,] heights;

	void OnGUI () {
		//生成高度图
		if (GUI.Button(new Rect(0, 0, 200, 40), "Generate PerlinNoise")) {
			noiseTexture = GeneratePerlinNoise(this.width, this.heiht, out heights);
			terrain.terrainData.SetHeights(0, 0, heights);
		}

		//保存高度图
		if (GUI.Button(new Rect(0, 50, 200, 40), "Save as RAW")) {
			string savePath = Application.dataPath + "/Heightmap.raw";
			Debug.Log(savePath);
			SaveRAW(savePath, noiseTexture);
			AssetDatabase.Refresh();
		}
	}

	// 生成柏林噪声图
	protected Texture2D GeneratePerlinNoise(int w, int h, out float[,] heights)
	{
		heights = new float[w+1, h+1];//维数长度对应顶点数
		Texture2D texture = new Texture2D(w, h, TextureFormat.RGB24, false);
		Color[] pixels = new Color[w * h];
		float y = 0.0F;
		float x = 0.0F;
        while (y < texture.height)
        {
            x = 0.0F;
            while (x < texture.width)
            {
                float xCoord = xOrg + x / texture.width * scale;
                float yCoord = yOrg + y / texture.height * scale;
                float sample = Mathf.PerlinNoise(xCoord, yCoord);
                pixels[(int)(y * texture.width + x)] = new Color(sample, sample, sample);
				heights[(int)y,(int)x] = sample;
                x++;
            }
            y++;
        }
        texture.SetPixels(pixels);
        texture.Apply();
		return texture;
	}

	// 保存高度图(.raw格式)
	protected void SaveRAW(string filePath, Texture2D texture) 
	{
		try{
			byte[] bytes = texture.GetRawTextureData();
			Debug.Log("bytes.Length="+bytes.Length);//w*h*3
			File.WriteAllBytes(filePath, bytes);
		}catch(Exception ex){
			Debug.Log(ex.StackTrace);
		}
	}
}

工程截图

3333.png

4444.png

6666.png

效果截图

Scene窗口

1111.png

2222.png

Game窗口

77777.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号