GLM 翻译问题

GLM translation issue

我有一个模型并想沿着它的轴移动它,如果我有一个变换矩阵 glm::mat4 并且向上向量是 glm::vec4 up(matrix[1]); 那么如果我想沿着向上向量移动模型按值 up*=d; 然后 matrix=glm::translate(matrix,up); ,结果矩阵不会向右移动模型,例如,如果向上向量 id (0,0.707106769,0.707106769) "the model is rotated around the X axis by 45d" 并且我想将它移动 5单位所以平移矢量是(0,3.535533845,3.535533845)然后在平移之后位置分量仅在Y方向改变所以它仅沿Y轴移动。

GLM 的 translate 源代码:

template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER mat<4, 4, T, Q> translate(mat<4, 4, T, Q> const& m, vec<3, T, Q> const& v)
{
    mat<4, 4, T, Q> Result(m);
    Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];
    return Result;
}

应用平移的效果由现有矩阵的旋转分量(左上角的 3x3 子矩阵,或者如果底行是 0 0 0 1 的前 3 列)修改,即:

glm::translate prepends, rather than appends, the translation.

也就是说,上面的代码相当于:

// create an identity matrix and apply the translation
glm::mat4 translation = glm::translate(glm::mat4(1.f), up);

// post-multiply (i.e. the applied translation comes FIRST)
matrix = matrix * translation;

你想要的效果可以通过以下方式实现:

1)

// pre-multiply (i.e. the applied translation comes AFTER)
matrix = translation * matrix;

或者等效地,在模型的 local 基础上构建翻译:

2)

// local up vector (Y-axis)
glm::vec3 local_up(0.f, 1.f, 0.f);
local_up *= d;

// apply using translate as before
matrix = glm::translate(matrix, local_up);