gpt4 book ai didi

c++ - OpenGL-在任意轴上平移对象

转载 作者:行者123 更新时间:2023-12-02 10:31:06 25 4
gpt4 key购买 nike

我有一个球体,也有一个通过其原点的轴。我想上下移动球体的轴。在它的起始位置没有问题,因为轴开始平行于全局y轴。但是,一旦我旋转球体,因此绕着z轴的球体轴也就变得复杂了。

我的第一个想法是对轴进行归一化,并简单地将其用作转换矩阵中的转换 vector 。然后将平移矩阵乘以归一化的轴,然后将球体推到轴上一个单位。

这是我已经得到的代码:

class Object
{
public:
inline Object()
: vao(0),
positionBuffer(0),
colorBuffer(0),
indexBuffer(0),
elements(0),
vertices(0)
{}

inline ~Object() { // GL context must exist on destruction
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &indexBuffer);
glDeleteBuffers(1, &colorBuffer);
glDeleteBuffers(1, &positionBuffer);
}

GLuint vao; // vertex-array-object ID

GLuint positionBuffer; // ID of vertex-buffer: position
GLuint colorBuffer; // ID of vertex-buffer: color

GLuint indexBuffer; // ID of index-buffer

GLuint elements; // Number of Elements

vector<glm::vec3> vertices;
glm::vec3 mp;

glm::mat4x4 model; // model matrix
};
glm::vec3 axis = glm::normalize(glm::vec3{ 
sphereax.vertices[0].x - sphereax.vertices[1].x,
sphereax.vertices[0].y - sphereax.vertices[1].y,
sphereax.vertices[0].z - sphereax.vertices[1].z}
);
translateObject(earth, axis);
void translateObject(Object &obj, glm::vec3 &translation)
{
glm::mat4x4 trans_mat = glm::translate(glm::mat4(1.0f), translation);
for (int i = 0; i < obj.vertices.size(); i++)
{
obj.vertices[i] = glm::vec3(glm::vec4(obj.vertices[i], 1.0f) * trans_mat);
}
obj.mp = glm::vec3(glm::vec4(obj.mp, 1.0f) * trans_mat);
}
translateObject();中的转换矩阵似乎是正确的,但是将点之一与转换矩阵相乘却没有效果。

最佳答案

我建议执行以下操作:

  • 围绕球的旋转轴旋转球
  • 通过球体沿x轴的中心距球体的距离来平移
  • 围绕世界中心旋转球体

  • glm::vec3 rotation_axis      = ...; // sphere axis
    float axis_rot_angle = ...; // current axis rotation angle in radians
    float distance_to_center = ...; // distance from the center of the world
    float world_rot_angle = ...; // current world rotation angle in radians

    glm::mat4 sphere_rot = glm::rotation(glm::mat4(1.0f), axis_rot_angle, rotation_axis);
    glm::mat4 sphere_trans = glm::translate(glm::mat4(1.0f), glm::vec3(distance_to_center, 0.0f, 0.0f));
    glm::mat4 world_rot = glm::rotation(glm::mat4(1.0f), world_rot_angle, glm::vec3(0.0f, 0.0f, 1.0f));

    glm::mat4 model_mat = world_rot * sphere_trans * sphere_rot;

    关于c++ - OpenGL-在任意轴上平移对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62267498/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com