矩阵乘法 - 如何让一个行星在它自己的轴上旋转,并绕着它的父轨道运行?

时间:2017-12-04 22:21:08

标签: c++ opengl glm-math

我有两颗行星,太阳和地球。我希望它们在自己的轴上旋转,同时绕行星运行。

我可以让这两种行为单独发挥作用,但我对如何将它们结合起来感到难过。

void planet::render() {
    mat4 axisPos = mat4(1.0f);
    axialRotation = rotate(axisPos, axisRotationSpeedConstant, vec3(0.0f, 1.0f, 0.0f));

    if (hostPlanet != NULL) {
        mat4 hostTransformPosition = mat4(1.0f);
        hostTransformPosition[3] = hostPlanet->getTransform()[3];
        orbitalSpeed += orbitalSpeedConstant;

        orbitRotation = rotate(hostTransformPosition, orbitalSpeed, vec3(0.0f, 1.0f, 0.0f));
        orbitRotation = translate(orbitRotation, vec3(distanceFromParent, 0.0f, 0.0f));

        //rotTransform will make them spin on their axis, but not orbit their parent planet
        mat4 rotTransform = transform * axialRotation;

        //transform *= rotTransform;

        //orbitRotation will make the planet orbit, but it won't spin on it's own axis.
        transform = orbitRotation;
    }
    else {
        transform *= axialRotation;
    }


    glUniform4fv(gColLoc, 1, &color[0]);
    glUniformMatrix4fv(gModelToWorldTransformLoc, 1, GL_FALSE, &getTransform()[0][0]);
    glDrawArrays(GL_LINES, 0, NUMVERTS);
};

1 个答案:

答案 0 :(得分:0)

哇噢!像往常一样,问这个问题让我能够回答它。在最后一行之后,知道transform[0 to 2]表示4x4矩阵中的旋转(transform[3]表示3D空间中的位置),我想用当前矩阵计算中的旋转替换当前矩阵计算。 Badabing,我得到了答案。

    transform = orbitRotation;
    transform[0] = rotTransform[0];
    transform[1] = rotTransform[1];
    transform[2] = rotTransform[2];