我正在使用旧版OpenGL,并尝试使用鼠标在顶点之间移动。要测试是否单击了某个顶点,我将遍历所有顶点并将它们乘以模型和投影矩阵,然后除以w值。效果很好,如下所示:
for (Vertex *vertex : context->getMesh().vertices) {
QVector4D vert(vertex->xPos, vertex->yPos, vertex->zPos, 1.0f);
QVector4D transformedVert = projectionMatrix * modelMatrix * vert;
transformedVert /= transformedVert.w();
if ((mappedX < (transformedVert.x() + 0.1) && mappedX > (transformedVert.x() - 0.1)) &&
(mappedY < (transformedVert.y() + 0.1) && mappedY > (transformedVert.y() - 0.1))) {
std::cout << "SUCCESS" << std::endl;
vertexPicked = true;
currentVertex = vertex;
}
}
然后,当我移动鼠标时,我尝试通过先将当前鼠标坐标乘以与第一步相同的W值,然后再乘以投影矩阵和模型矩阵的逆来进行反向操作。这会将顶点移动到周围,但不会移动到鼠标所在的位置。
float mouseX = ((2.0f * event->x()) / width() - 1.0f);
float mouseY = -((2.0f * event->y()) / height() - 1.0f);
float x = (modelMatrix.inverted() * projectionMatrix.inverted() *
(QVector4D(mouseX, mouseY, 1, 1) * (projectionMatrix * modelMatrix * QVector4D(MousePicker::currentVertex->xPos, MousePicker::currentVertex->yPos, MousePicker::currentVertex->zPos, 1)).w())).x();
MousePicker::currentVertex->xPos = x;
我目前仅在尝试更改X坐标。