- Home /
Question by
CaptainChristian · Jul 02, 2013 at 11:55 AM ·
terrainobjectsnap
Snap Terrain to Building/Structure
Hi,
I would like my terrain to snap to buildings placed on it. I got the basics, but I cannot get it to work correctly. Sometimes the results go into the right direction, however often they are far off.
In a nutshell I use the transform position as a reference height and then interpolate between the lower vectors of the bounding volume. The code for terraforming itself can be found on the forums already, but I will post it to show where I am standing currently.
float distance = Vector3.Distance (start, end);
float segmentSize = 0.2f;
int tiles = Mathf.CeilToInt (distance / segmentSize);
for (int t = 0; t < tiles; t++) {
Vector3 tempPosition = Vector3.Lerp (start, end, t / (tiles-1));
Terrain tempTerrain = GetTerrainTile(tempPosition);
// get the normalized position of this game object relative to the terrain
Vector3 tempCoord = (tempPosition - tempTerrain.gameObject.transform.position);
Vector3 tempCoordNormalized = new Vector3(0,0,0);
tempCoordNormalized.x = tempCoord.x / tempTerrain.terrainData.size.x;
tempCoordNormalized.y = tempCoord.y / tempTerrain.terrainData.size.y;
tempCoordNormalized.z = tempCoord.z / tempTerrain.terrainData.size.z;
// get the position of the terrain heightmap where this game object is
posXInTerrain = (int)(tempCoordNormalized.x * tempTerrain.terrainData.heightmapWidth);
posYInTerrain = (int)(tempCoordNormalized.z * tempTerrain.terrainData.heightmapWidth);
// we set an offset so that all the raising terrain is under this game object
int size = 1;
float desiredHeight = height/tempTerrain.terrainData.heightmapScale.y;
// get the heights of the terrain under this game object
float[,] heights = tempTerrain.terrainData.GetHeights (posXInTerrain, posYInTerrain, size, size);
// we set each sample of the terrain in the size to the desired height
for (int i=0; i<size; i++)
for (int j=0; j<size; j++)
heights [i, j] = desiredHeight;
// set the new height
tempTerrain.terrainData.SetHeights (posXInTerrain, posYInTerrain, heights);
}
Any help or hint would be appreciated.
Comment
Your answer
Follow this Question
Related Questions
Object falls through terrain 1 Answer
Raycast Snapping Problem. 0 Answers
Object falling through terrain with script 2 Answers
Export Whole Scene to 3ds Max 2 Answers