gpt4 book ai didi

c++ - 使用 glm::unproject() 获取 Z = 0 平面上的光标位置?

转载 作者:行者123 更新时间:2023-12-02 02:29:29 26 4
gpt4 key购买 nike

我试图仅使用光标坐标来获取网格(z = 0)的坐标(x,y)。经过长时间的搜索,我发现使用 glm::unproject 可以实现这一点。

首先,我使用回调获取光标坐标:

void cursorCallback(GLFWwindow *window, double x, double y)
{
this->cursorCoordinate = glm::vec3(x, (this->windowHeight - y - 1.0f), 0.0f);
}

然后转换这些坐标:

glm::vec3 cursorCoordinatesToWorldCoordinates()
{
glm::vec3 pointInitial = glm::unProject(
glm::vec3(this->cursorCoordinate.x, this->cursorCoordinate.y, 0.0),
this->modelMatrix * this->viewMatrix,
this->projectionMatrix,
this->viewPort
);

glm::vec3 pointFinal = glm::unProject(
glm::vec3(this->cursorCoordinate.x, this->cursorCoordinate.y, 1.0),
this->modelMatrix * this->viewMatrix,
this->projectionMatrix,
this->viewPort
);

glm::vec3 vectorDirector = pointFinal - pointInitial;

double lambda = (-pointInitial.y) / vectorDirector.y;

double x = pointInitial.x + lambda * vectorDirector.x;
double y = pointInitial.z + lambda * vectorDirector.z;

return glm::vec3(x, y, 0.0f);
}

我使用 ArcBall 相机围绕指定轴旋转世界,这就是我生成 MVP 矩阵的方式:

this->position = glm::vec3(0.0f, 10.0f, 5.0f);
this->up = glm::vec3(0.0f, 1.0f, 0.0f);
this->lookAt = glm::vec3(0.0f, 0.0f, 0.0f);

this->fieldView = 99.0f;
this->farDistance = 100.0f;
this->nearDistance = 0.1f;

this->modelMatrix = glm::mat4(1.0f);
this->viewMatrix = glm::lookAt(this->position, this->lookAt, this->up) * glm::rotate(glm::degrees(this->rotationAngle) * this->dragSpeed, this->rotationAxis);
this->projectionMatrix = glm::perspective(glm::radians(this->fieldView), 1.0f, this->nearDistance, this->farDistance);

但是出了点问题,因为我没有得到正确的结果。查看该应用程序的打印:

enter image description here

每个正方形为 1 个单位,立方体渲染在位置 (0, 0, 0)。 rotationAngle = 0 当 a 将光标置于 (0,0), (1,1), (2,2), (3,3), (4,4), (5, 5)我分别得到(0, 5.7)、(0.8, 6.4)、(1.6, 6.9)、(2.4, 7.6)、(3.2, 8.2)、(4.2, 8.8)。这不是预期的。

  • 为什么 y 延迟了 6 个单位?
  • 有必要根据 rotationAngle 旋转结果 cursorCooperativesToWorldCooperatives 不是吗?

--

我已经这样做了:

  • 检查视口(viewport)是否与 glViewport 匹配 - 确定
  • 检查了 opengl 坐标(Y 向上,而不是 Z) - 确定

最佳答案

您想要将光线从 glm::vec3(this->cursorCooperative.x, this->cursorCooperative.y, 0.0) 相交到 glm::vec3(this->光标坐标.x, this->光标坐标.y, 1.0) 与世界空间中的网格,而不是模型空间(长方体)。您必须跳过 this.modelMatrix:

glm::vec3 pointInitial = glm::unProject(
glm::vec3(this->cursorCoordinate.x, this->cursorCoordinate.y, 0.0),
this->viewMatrix,
this->projectionMatrix,
this->viewPort);

glm::vec3 pointFinal = glm::unProject(
glm::vec3(this->cursorCoordinate.x, this->cursorCoordinate.y, 1.0),
this->viewMatrix,
this->projectionMatrix,
this->viewPort);
<小时/>

无论如何,this->modelMatrix * this->viewMatrix 都是不正确的。如果您想让光线与模型空间中的对象相交,那么它必须是 this->viewMatrix * this->modelMatrix。矩阵乘法不是Commutative .

关于c++ - 使用 glm::unproject() 获取 Z = 0 平面上的光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com