I generated a virtual terrain consisting of quads in my code I am now trying to find the height of the terrain at a certain point. To clarify: I have a terrain with a width and depth in X and Y directions, and a height in the Z direction. I want to know at what Z a line at a specific X and Y intersects my plane.
The terrain itself is stored as quads in a two-dimensional array (the indices are the coords, I just store the height) and I'm using the following code:
(it uses the cross product of the vectors from the bottom left to bottom right and top left points)
function getTerrainHeight(float x, float y) {
int ix = (int)x;
int iy = (int)y;
Vector3 V1 = new Vector3(ix,iy,heights[ix][iy]);
Vector3 V2 = new Vector3(ix+1, iy, heights[ix + 1][iy]);
Vector3 V3 = new Vector3(ix, iy+1, heights[ix][iy+1]);
if ((x-ix) + (y-iy) > 1)
{
V1 = new Vector3(ix + 1, iy + 1, heights[ix + 1][iy + 1]);
}
Vector3 cross = Vector3.Cross(V2-V1,V3-V1);
return (cross.X * (x - ix) + cross.Y * (y - iy)) / -cross.Z + heights[ix][iy];
}
This kinda works, but there are some mismatches, when I go over the terrain there are alway some dents where the height is lower than it should be. Does anybody know what's going wrong?