繁体   English   中英

如何使用 GLM OpenGL C++ 围绕一个点旋转 object?

[英]How to rotate an object around a point with GLM OpenGL C++?

我正在尝试做这样的事情,但由于某种原因,我的立方体仍然围绕原点旋转。 我究竟做错了什么?

glm::mat4 identity = glm::mat4(1.0f); // construct identity matrix

glm::mat4 trans;
glm::mat4 rot;
glm::mat4 transBack;
glm::mat4 M;

glm::vec4 br = glm::vec4(currentPositionX - 0.4, 0.0f, currentPositionZ + 1.2, 1.0f);

//get the matrix transformation to translate
trans = glm::translate(identity, glm::vec3(+0.4, 0.0f, -1.2));

identity = glm::mat4(1.0f); // construct identity matrix
//get the matrix transformation to rotate
rot = glm::rotate(identity, glm::radians(rotation), glm::vec3(0.0, 1.0, 0.0));  // rotate with car ROT -

identity = glm::mat4(1.0f); // construct identity matrix
//get the matrix transformation to translate
transBack = glm::translate(identity, glm::vec3(-0.4, 0.0f, +1.2));

M = transBack * rot * trans;

// A' = M . A , A being a point 
br = M * br;

围绕(x,y,z)旋转一个点的公式是:

T(x,y,z) * R * T(-x,-y,-z)   // operations are combined from right to left

您必须将点P(x,y,z)移动到区域设置坐标系的中心,应用旋转并平移回世界空间。

auto rotAroundPoint(float rad, const glm::vec3& point, const glm::vec3& axis)
{
auto t1 = glm::translate(glm::mat4(1),-point);
auto r = glm::rotate(glm::mat4(1),rad,axis);
auto t2 = glm::translate(glm::mat4(1),point);
return t2 * r * t1;
}

int main() {
glm::vec4 geom(0,0,0,1); // one point of cube geometry
glm::vec3 o(6,0,6); // origin of rotation
glm::vec3 cp(5,0,5); // current position of cube
for (float deg : {0.f,90.f,180.f,270.f}) {
    auto res = rotAroundPoint(glm::radians(deg),o,glm::vec3(0,1,0)) * 
        glm::translate(glm::mat4(1),cp) * geom;
    std::cout << glm::to_string(res) << std::endl;
}
/*
      ------------------> x
      |
      |
      |            cp(5,5)         (7,5)
      |                    o(6,6)
      |            (5,7)           (7,7)
      |
      z
*/

神栓演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM