glm::unProject issues, world to screen space alignment error

烂漫一生 提交于 2019-12-25 06:35:36

问题


I have a plane in 3D space, which is facing the camera that I want to be able to place at the same position as where I click. However, the position of the plane overshoots the mouse cursor. This is for a dynamic GUI that I want to be able to move about and interact with the widgets on the UI.

void mouse::unProjectMouse(float width, float height, camera* viewportCamera)
{
    if(NULL == viewportCamera)
    {
        std::cout<<CNTRLCALL<<"camera failed! failed to un-project mouse";
    } else {
        glm::vec4 viewport = glm::vec4(0, 0, width, height);
        glm::mat4 tmpView = viewportCamera->updateView();
        glm::mat4 tmpProj = viewportCamera->updateProjection();
        glm::vec3 screenPos = glm::vec3(mouseX, height-mouseY - 1.0f, 1.0f);

        glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);

        worldPos = worldPos / (worldPos.z * -1.0f);

        mouseWorldX = worldPos.x;
        mouseWorldY = worldPos.y;
        mouseWorldZ = worldPos.z;
    }
}

I am at a loss here as to why the plane is not aligning correctly with the mouse.


回答1:


This is the fix:

  void mouse::unProjectMouse(float width, float height, camera* viewportCamera)
{
if(NULL == viewportCamera)
{
    std::cout<<CNTRLCALL<<"camera failed! failed to un-project mouse";
} else {


    glm::vec4 viewport = glm::vec4(0.0f, 0.0f, width, height);
    glm::mat4 tmpView = glm::lookAt(glm::vec3(viewportCamera->getCameraPosX(),viewportCamera->getCameraPosY(),viewportCamera->getCameraPosZ()),
                                    glm::vec3(viewportCamera->getForward().x,viewportCamera->getForward().y,viewportCamera->getForward().z),glm::vec3(0,1,0));
    glm::mat4 tmpProj = glm::perspective( 90.0f, width/height, 0.1f, 1000.0f);
    glm::vec3 screenPos = glm::vec3(mouseX, height-mouseY - 1, 0.0f);

    glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);

    mouseWorldX = worldPos.x;
    mouseWorldY = worldPos.y;
    mouseWorldZ = worldPos.z;
}

}

And then to align the object to the cursors positon, the Z element of the camera had to be exact:

UIcamera->translateCameraX(0.0f);
UIcamera->translateCameraY(0.0f);
UIcamera->translateCameraZ(0.744f);


来源:https://stackoverflow.com/questions/15709045/glmunproject-issues-world-to-screen-space-alignment-error

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