0

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?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Perry
  • 98
  • 7
  • It feels wrong since you are using just 3 points out of 4, so if you quads are not flat (which is often the case) the heights on second triangle of the quad would be completely off... – Alexei Levenkov Jun 04 '13 at 16:21
  • You're right come to think of it, any idea how I could encorporate that fourth point? Or should I figure out the triangle i'm on (if I look at my quads as 2 triangles)? – Perry Jun 04 '13 at 16:46
  • Figuring out what triangle you are one is likely correct approach (should be simple checks), make sure it aligns with your actual triangles you draw. – Alexei Levenkov Jun 04 '13 at 17:30
  • updated with my triangle check, I'm still experiencing the same problem though. – Perry Jun 04 '13 at 18:30

0 Answers0