1

我试图将方向向量指向我的光标在屏幕上的位置,但是它给了我很大的值而不是实际值。在进行鼠标选择时,我的世界坐标得到的数字非常少,例如

Mouse is pointing at World X: 4.03225e-05 Y: -0.00048387 Z: -1

我在这里做错了什么吗,我已经从这里改编了这段代码。我glm::intersectLineTriangle()用来测试这条线是否指向有问题的三角形世界坐标。

以下是相关代码:

double mouse_x, mouse_y;
glfwGetCursorPos(GL::g_window, &mouse_x, &mouse_y);

int width, height;
glfwGetFramebufferSize(GL::g_window, &width, &height);

// these positions must be in range [-1, 1] (!!!), not [0, width] and [0, height]
float mouseX = (float)mouse_x / ((float)width  * 0.5f) - 1.0f;
float mouseY = (float)mouse_y / ((float)height * 0.5f) - 1.0f;

glm::mat4 invVP = glm::inverse(projection * view);
glm::vec4 screenPos = glm::vec4(mouseX, -mouseY, 1.0f, 1.0f);
glm::vec4 worldPos = invVP * screenPos;

glm::vec3 mouseClickVec = glm::normalize(glm::vec3(worldPos));

std::cout << "Mouse is pointing at World X: " << mouseClickVec.x <<  " Y: " << mouseClickVec.y << " Z: " << mouseClickVec.z << '\n';

glm::vec3 intersect;

if(glm::intersectLineTriangle(glm::vec3(0.0f, 0.0f, 0.0f), mouseClickVec, m_vertices_world[0], m_vertices_world[0], m_vertices_world[0], intersect))
{
 std::cout << "Intersect at X: " << intersect.x <<  " Y: " << intersect.y << " Z: " << intersect.z << '\n';
 setColor(glm::vec4(0.0f, 0.0f, 1.0f, 1.0f));
}
else
{
    setColor(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
}
4

1 回答 1

1

使用正交(平行)投影时,视点不是(0,0,0),(不在视图空间,当然也不在世界空间)。您必须创建一条从近平面 (-1) 到远平面 (1) 的射线:

glm::vec4 worldPosFar = invVP * glm::vec4(mouseX, -mouseY, 1.0f, 1.0f);
glm::vec3 mouseClickVecFar = glm::normalize(glm::vec3(worldPosFar));

glm::vec4 worldPosNear = invVP * glm::vec4(mouseX, -mouseY, -1.0f, 1.0f);
glm::vec3 mouseClickVecNear = glm::normalize(glm::vec3(worldPosNear));

if (glm::intersectLineTriangle(mouseClickVecNear, mouseClickVecFar,
    m_vertices_world[0], m_vertices_world[0], m_vertices_world[0], intersect))
{
    // [...]
}
于 2021-10-17T21:04:29.153 回答