Search code examples
c++glm-math

XYZ Distance point-to-point of two glm::mat4 matrices


I have two glm::mat4 modelview matrices and I need to compare the distance between the two xyz points, I tried this code but it doesnt seem to be accurate;

inline GLfloat Dist3D(GLfloat X1, GLfloat Y1, GLfloat Z1,
    GLfloat X2, GLfloat Y2, GLfloat Z2) {
    return sqrt(pow((X2 - X1), 2) + pow((Y2 - Y1), 2) + pow((Z2 - Z1), 2));
}
void PlayerScore::CompareMatrixes(
    glm::mat4 Target,
    glm::mat4 Source) {

    GLfloat dist = Dist3D(
        Target[3][0], Target[3][1], Target[3][2],
        Source[3][0], Source[3][1], Source[3][2]);

    printf("Dist to target %f\n", dist);
}

Solution

  • You can simply use glm::length to determine the distance between two points.

    glm::vec3 v1 = {2.0, 0.0, 0.0};
    glm::vec3 v2 = {6.0, 0.0, 0.0};
    
    auto distance = glm::length(v2 - v1);
    
    std::cout << distance << std::endl; // expected output is 4
    
    glm::mat4 identity(1.0);
    
    glm::mat4 m1 = glm::translate(identity, v1);
    glm::mat4 m2 = glm::translate(identity, v2);
    
    // note that the operator[] returns an entire column as vec4
    distance = glm::length(m2[3] - m1[3]);
    
    std::cout << distance << std::endl; // expected output is 4