- Home /
Question by
KaidaStudios · May 28, 2019 at 10:57 PM ·
textureterrainruntimealphamap
Update Terrain Texture at Object Location at runtime
Hello Unity Community! I need some advice on getting the terrain texture to appear where the indent is, I got it to the same size but it keeps spawning in the corner, any help would be greatly appreciated!
Here is my code.. Sorry for the mess. Also if theres an easy fix to making the indent blend more, I would appreciate being pointed in the right direction! Thank you!
//////////////////// SET COORDINATES & FLOATS ////////////////////////
// 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);
float[,,] map = new float[size, size, 2];
//////////////////// UPDATE TEXTURE ////////////////////////
// For each point on the alphamap...
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
// Get the normalized terrain coordinate that
// corresponds to the the point.
float normX = x * 1.0f / (size - 1);
float normY = y * 1.0f / (size - 1);
// Get the steepness value at the normalized coordinate.
var angle = terr.terrainData.GetSteepness(normX, normY);
// Steepness is given as an angle, 0..90 degrees. Divide
// by 90 to get an alpha blending value in the range 0..1.
var frac = angle / 90.0;
map[x, y, 0] = (float)frac;
map[x, y, 1] = (float)(1 - frac);
}
}
//////////////////// UPDATE HEIGHT ////////////////////////
// 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 NEW CONDITIONS ////////////////////////
terr.terrainData.SetHeights(posXInTerrain-offset,posYInTerrain-offset,heights);
terr.terrainData.SetAlphamaps(0, 0, map);
terr.Flush();
wrong-location.png
(376.6 kB)
Comment
Your answer
Follow this Question
Related Questions
how to assign texture on the terrain at runtime 0 Answers
Change texture on terrain based on Vector3 at runtime 0 Answers
Texturing terrain at runtime 1 Answer
Assigning Textures to Terrain at Runtime 2 Answers
Create alphamap from mesh 0 Answers