1
\$\begingroup\$

Hello everyone I'm programming a game with c++ and openGL. My world is generated from a heightmap (100x100 matrix with values 0-255) and now I need a function that returns the actual height based on which triangle of the heightmap I am. I wrote this code

float Terrain::getCollisionHeight(float x, float z) {
    float x_pos = x / lato;
    float z_pos = z / lato;

    float _x = x-x_pos;
    float _z = z-z_pos;

    float m = _x / _z;

    float hp0 = hm->getHeight(x_pos,     z_pos)     / divider;
    float hp3 = hm->getHeight(x_pos + 1, z_pos)     / divider;
    float hp2 = hm->getHeight(x_pos + 1, z_pos + 1) / divider;
    float hp1 = hm->getHeight(x_pos,     z_pos + 1) / divider;
    cout << "HP: " << hp0 << " " << hp1 << " " << hp2 << " " << hp3 << endl;
    if (_x >= _z) {
        cout << "Upper triangle" << endl;
        float zp12;
        if (_z == 0) zp12 = lato;
        else zp12 = m*lato;
        float i1 = hp1 + (hp2 - hp1)*zp12/lato; 
        return hp0 + (i1 - hp0)*_z / sqrt(0.5*0.5 + zp12*zp12);
    } else {
        float xp23;
        if (_z == 0) xp23 = lato;
        else xp23 = m*lato;
        float i1 = hp2 + (hp3 - hp2)*xp23 / lato;
        return hp0 + (i1 - hp0)*_x / sqrt(0.5*0.5 + xp23*xp23);
    }

but it returns wrong values (e.g. when i interpolate 135 and 117 it returns something like 140 which is greater than both of them). The cases are separated because i always draw two triangles merged as a square. Can you help me returning the right interpolation value? Thanks a lot

\$\endgroup\$
  • \$\begingroup\$ Your code is terribly confusing and hard to follow, could you improve the variable names and add some comments explaining what it does? \$\endgroup\$ – Tim Jan 27 '16 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.