我正在使用旧版 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 坐标。