Hello everyone, I’m having a lot of difficulty dynamically altering the terrain.
I have a GameObject to which I’ve attached the following script that was cobbled together from other answers. The intent is to make the left mouse click cause the piece of terrain under the GameObject to raise. It doesn’t appear to do anything but the script completes successfully. My character is standing near the GameObject while testing. Any ideas? ![]()
void Update () {
if(Input.GetMouseButton(0))
{
Terrain terrain = Terrain.activeTerrain;
Vector3 pos = GetTerrainRelativePosition();
int x = (int)pos.x;
int y = (int)pos.y;
int size = 50; // the diameter of terrain portion that will raise under the game object
float desiredHeight = 0; // the height we want that portion of terrain to be
float[,] heights = terrain.terrainData.GetHeights(x, y, 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;
// go raising the terrain slowly
desiredHeight += Time.deltaTime;
// set the new height
terrain.terrainData.SetHeights(x, y, heights);
}
}
private Vector3 GetTerrainRelativePosition()
{
Terrain terrain = Terrain.activeTerrain;
Vector3 tempCoord = transform.position - terrain.gameObject.transform.position;
Vector3 coord;
coord.x = tempCoord.x / terrain.terrainData.size.x;
coord.y = tempCoord.y / terrain.terrainData.size.y;
coord.z = tempCoord.z / terrain.terrainData.size.z;
int hmWidth = terrain.terrainData.heightmapWidth;
int hmHeight = terrain.terrainData.heightmapHeight;
// get the position of the terrain heightmap where this game object is
float posXInTerrain = coord.x * hmWidth;
float posYInTerrain = coord.z * hmHeight;
return new Vector3(posXInTerrain, posYInTerrain);
}
Thanks!
Vince