I’m writing a script that reads a heightmap from a binary text file, and programmatically sets said heightmap to the active terrain. To do this for an 8bit heightmap, it’s pretty simple: I just read each byte in the text file, store it in a byte array, translate that into a float matrix, and load the heightmap using terrain.terrainData.SetHeights(0, 0, float) (See code at the end for actual implementation).
This works, but the resolution of the terrain is pretty bad, as the elevations look kind of like stairs. Because of this, I’m going to have to use a 16bit heightmap, but I don’t know how to interpret the bytes from the binary text file, as I don’t know how they’re organized. I’m assuming the corresponding pair of bytes used to represent each elevation value is side by side…?
Here’s the current (working) code for the 8bit heightmap:
using UnityEngine;
using System.Collections;
public class TerrainGenerate : MonoBehaviour
{
public TextAsset binaryData;
private Terrain terrain; // terrain to modify
protected int heightmapWidth; // heightmap width
protected int heightmapHeight; // heightmap height
void Start ()
{
terrain = Terrain.activeTerrain;
heightmapWidth = terrain.terrainData.heightmapWidth;
heightmapHeight = terrain.terrainData.heightmapHeight;
byte[] bytes = binaryData.bytes; // Loads the whole heightmap file into this array
float[,] heightmap = new float[heightmapWidth,heightmapHeight];
int byteNumber = 0; // Will be used to iterate through the 'bytes' array
for(int width = 0; width < bytes.Length/heightmapHeight; width++)
{
for(int height = 0; height < bytes.Length/heightmapHeight; height++)
{
heightmap[width, height] = bytes[byteNumber]/256.0f; // Sets value in 'bytes' array to matrix
byteNumber++;
}
}
terrain.terrainData.SetHeights(0, 0, heightmap); // Loads matrix into terrain.
}
}