Reputation: 21
Currently the terrain under the object the script is on, the terrain will go to the max height. Can i somehow have a variable to set it to a specified height?
I didn't try too much, because i don't know how this works all too good..
using System.Collections; using System.Collections.Generic; using
UnityEngine;
public class test : MonoBehaviour {
public Terrain terr; // terrain to modify
int hmWidth; // heightmap width
int hmHeight; // heightmap height
int posXInTerrain; // position of the game object in terrain width (x axis)
int posYInTerrain; // position of the game object in terrain height (z axis)
int size = 5; // the diameter of terrain portion that will raise under the game object
float desiredHeight = 2; // the height we want that portion of terrain to be
void Start()
{
terr = Terrain.activeTerrain;
hmWidth = terr.terrainData.heightmapWidth;
hmHeight = terr.terrainData.heightmapHeight;
}
void Update()
{
// get the normalized position of this game object relative to the terrain
Vector3 tempCoord = (transform.position - terr.gameObject.transform.position);
Vector3 coord;
coord.x = tempCoord.x / terr.terrainData.size.x;
coord.y = tempCoord.y / terr.terrainData.size.y;
coord.z = tempCoord.z / terr.terrainData.size.z;
// get the position of the terrain heightmap where this game object is
posXInTerrain = (int)(coord.x * hmWidth);
posYInTerrain = (int)(coord.z * hmHeight);
// we set an offset so that all the raising terrain is under this game object
int offset = size / 2;
// get the heights of the terrain under this game object
float[,] heights = terr.terrainData.GetHeights(posXInTerrain - offset, posYInTerrain - offset, 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
terr.terrainData.SetHeights(posXInTerrain - offset, posYInTerrain - offset, heights);
}
}
I expect to have an input and have the height set to the inputted height.
Example: input = 10 terrain under the object goes to 10
actual output: input - 10 terrain under the object goes to 600
Upvotes: 1
Views: 3236
Reputation: 31
The heights you pass to SetHeights
method should be between 0 and 1. 0 means 0, 1 means maximum height of the terrain.
var heightScale = 1.0f / terr.terrainData.size.y;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
heights[i, j] = desiredHeight * heigthScale;
Upvotes: 0