Search code examples
c++glm-math

glm translation of vec4 not working (x and y do not change) despite scale and rotate working fine


When using glm translation on a mat4 and multiplying it by a vec4, x and y are inexplicably completely unaffected and appear the same as if I had translated in the first place. Is there something I'm just not understanding?

mat4 c = mat4(1.f);
c = translate(c, vec3(10, 10, 0))
vec4 dv1 = vec4(line1s[i].x, line1s[i].y, 1.f, 1.f) * c

x and y should be affected by this, right?


Solution

  • The order of multiplication is incorrect in your code. In your example:

    vec4 dv1 = vec4(line1s[i].x, line1s[i].y, 1.f, 1.f) * c;
    

    You should multiply the matrix by the vector, not the other way around:

    vec4 dv1 = c * vec4(line1s[i].x, line1s[i].y, 1.f, 1.f);
    

    As explained in gamedev.stackexchange.com, the correct formula for matrix-vector multiplication is:

    (x*a + y*b + z*c + w*d;
     x*e + y*f + z*g + w*h;
     x*i + y*j + z*k + w*l;
     x*m + y*n + z*o + w*p)
    

    So, when you multiply a matrix c by a vector vec4(line1s[i].x, line1s[i].y, 1.f, 1.f), the translation part of the matrix (last column) will affect the resulting vector's x and y components as expected.

    Make sure that the w component of the vec4 is set to 1, as mentioned in stackoverflow.com and gamedev.net, which is required for translations to work correctly in homogeneous coordinates.