Unity3d 保存和使用地形高度

TerrainHeightProcesser 地形高度存储工具

TerrainHeightData 地形高度数据

 

// class TerrainHeightProcesser

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

/*
 * 地形高度处理器
 */
public class TerrainHeightProcesser : ScriptableWizard
{

	public int mapWdith;
	public int mapHeight;


	[MenuItem("Tools/Save Terrain Height File")]
	public static void OpenDialog()
	{
		DisplayWizard<TerrainHeightProcesser>("Save Terrain Height", "Save", "Cancel");
	}

	public void SaveTerrainHeightFile()
	{

		//以每米为间隔从高空向下发射射线
		Vector3 pos = Vector3.zero;
		pos.y = 100;
		Ray ray = new Ray(pos, -Vector3.up);
		Vector3 targetPos = Vector3.zero;

		//创建一个对象
		TerrainHeightData th = ScriptableObject.CreateInstance<TerrainHeightData>();
		th.MapWidth = mapWdith;
		th.MapHeight = mapHeight;
		th.List = new List<float>();

		//纵向
		for (short i = 0; i < mapHeight; i++)
		{
			pos.z = i;
			//横向
			for (short j = 0; j < mapWdith; j++)
			{
				targetPos = Vector3.zero;//默认zero

				pos.x = j;
				ray.origin = pos;
				RaycastHit result;
				if (Physics.Raycast(ray, out result))
				{
					targetPos = result.point;
				}
				th.List.Add(targetPos.y);
			}
		}
		
		//计算file name
		string sceneName = UnityEditor.EditorApplication.currentScene;
		int start = sceneName.LastIndexOf('/') + 1;
		int count = sceneName.LastIndexOf('.')-start;
		sceneName = sceneName.Substring(start, count);
		string path = "Assets/ArtAsset/TerrainHeightData/" + sceneName + ".asset";

		//保存
		AssetDatabase.CreateAsset(th, path);
		AssetDatabase.Refresh();

		string str = string.Empty;
		str += "mapHeight=" + mapHeight.ToString() + "   ";
		str += "mapWdith=" + mapWdith.ToString();
		EditorUtility.DisplayDialog("SUCCESS", "file:" + path + "\n" + str, "OK");
	}

	void OnWizardCreate()
	{
		SaveTerrainHeightFile();
	}

	void OnWizardOtherButton()
	{
		Close();
	}

	
}

  

 

//TerrainHeightData

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

public class TerrainHeightData : ScriptableObject
{
	[SerializeField]
	public int MapWidth = 0;

	[SerializeField]
	public int MapHeight = 0;

	[SerializeField]
	public List<float> List;

	public float GetTerrainHeight(float x,float z)
	{
		int w = (int)Mathf.Floor(x);
		int h = (int)Mathf.Floor(z);
		if (w < 0 || w >= MapWidth || h < 0 || h >= MapHeight)
			return 0.0f;

		int idx = h*MapWidth+w;
		if (idx < 0 || idx >= MapWidth * MapHeight || idx >= List.Count)
			return 0.0f;

		return List[idx];
	}


}

  

posted @ 2015-09-15 11:43  MrBlue  阅读(1958)  评论(0编辑  收藏  举报