OpenGL moving vertices with mouse

时光毁灭记忆、已成空白 提交于 2019-12-12 01:13:14

问题


I am using legacy OpenGL and trying to move vertices around with the mouse. To test whether a vertex is clicked on I loop through all vertices and multiply them by the model and projection matrix before dividing by the w value. This works fine and is shown below:

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;
        }
    }

Then when I move the mouse I try to work backwards by first multiplying the current mouse coordinates by the same W value as in the first step and then multiplying by the inverse of the projection and model matrices. This moves the vertex around but not to where the mouse is.

  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;

I am currently only trying to change the X coordinate.

来源:https://stackoverflow.com/questions/54462354/opengl-moving-vertices-with-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!