translate的GLM源代码:
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::translateprepends,而不是appends,翻译。
也就是说,上面的代码等价于:
// 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);