- Home /
Question by
Malwallace12 · Oct 09, 2016 at 07:48 AM ·
c#scripting problemterrain
Why is my terrain lowering when editted at runtime to raise?
This is the code. using UnityEngine; using System.Collections;
public class TerrainEditor:MonoBehaviour {
public float brushSize;
public float smoothingFactor;
public int resWidth;
public int resHeight;
public float[,] heights;
public float[,] savedHeights;
public Terrain terrain;
// Use this for initialization
void Start () {
brushSize = 1;
terrain = gameObject.GetComponent<Terrain>();
resWidth = terrain.terrainData.heightmapWidth;
resHeight = terrain.terrainData.heightmapHeight;
heights = terrain.terrainData.GetHeights(0,0,resWidth,resHeight);
savedHeights = heights;
}
// Update is called once per frame
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetMouseButtonDown(0)){
if(Physics.Raycast(ray, out hit))
{
raiseTerrain(hit.point);
}
}
}
void OnDestroy()
{
terrain.terrainData.SetHeights(0, 0, savedHeights);
}
void raiseTerrain(Vector3 point)
{
int terX = (int)((point.x / terrain.terrainData.size.x) * resWidth);
int terZ = (int)((point.z / terrain.terrainData.size.z) * resHeight);
float[,] newHeight = new float[1, 1];
float y = heights[terX, terZ];
y += 0.01f * Time.deltaTime;
newHeight[0, 0] = y;
heights[terX, terZ] = y;
terrain.terrainData.SetHeights(terX, terZ, newHeight);
}
}
I have checked over this repeatedly and I just can not figure out what I'm doing wrong. I have an increase in the value, but the terrain is lowered. Please help...
Comment
Well, the first thing that strikes me is that the heights array is indexed as [y,x], not [x,y], so you need to adjust lines 45 and 49. See https://docs.unity3d.com/ScriptReference/TerrainData.SetHeights.html
Thank you so much! That was exactly the problem.