My terrain already exists, and has been painted.

I'm trying to mask out areas of my terrain so I can "zone" object spawns. For example, I want to spawn branches and logs randomly on a beach over time but I need to clearly identify "beach".

My best solution so far is to use a texture mask. I exported my heightmap to a PNG, filtered out areas I don't want, but I see no way to accurately find the exact terrain coordinate because my heightmap is 1024 resolution but my terrain is 400. Scaling the heightmap coords to terrain coords gets close but I can't tell what Unity does internally to match it.

Here's how I scale those heightmap array coords to world coords:

// Vector2 heightMap is a randomly chosen coord. I sample random coords
// of the texture looking for white (with a max number of tries)
// if I find a coord, I try to convert it...

var xScale = Terrain.activeTerrain.terrainData.size.x / TextureMask.width;
var zScale = Terrain.activeTerrain.terrainData.size.z / TextureMask.width;

var terrainPos = Terrain.activeTerrain.transform.position;

var scaledX = heightMap.x * xScale;
var scaledZ = heightMap.y * zScale;

var wx = scaledX + terrainPos.x;
var wz = scaledZ + terrainPos.z;

var y = Terrain.activeTerrain.SampleHeight(new Vector3(wx, 0, wz));

Are there better ways to mask our areas of my terrain, or is this mask system a good approach and I'm just missing details?

  • \$\begingroup\$ Are you looking to procedurally generate a map? If so, then you could look into perlin noise. Generate two images: one for height, and another for "biome" \$\endgroup\$ – Ian Young Nov 12 '19 at 8:44
  • \$\begingroup\$ No, I explained what I'm trying to do - randomly spawn objects in certain regions, defined by a mask. \$\endgroup\$ – BotskoNet Nov 12 '19 at 16:32
  • \$\begingroup\$ Instead of trying to map from the texture to the terrain, you can also try just picking a random spot on the terrain and then seeing if the texture is what you want. If so, spawn a thing you want there, if not, just skip or do some other thing. \$\endgroup\$ – John Hamilton Nov 21 '19 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.