C++ 在使用glm::ortho的2d游戏中,如何将像素坐标转换为opengl坐标?

C++ 在使用glm::ortho的2d游戏中,如何将像素坐标转换为opengl坐标?,c++,opengl,2d,glm-math,C++,Opengl,2d,Glm Math,我一直在尝试如何将像素坐标转换为opengl坐标,以便在游戏中使用鼠标进行某些操作,我尝试了许多操作,但每次都失败了,下面是我的代码: glm::mat4 anim; glm::mat4 model; model = glm::translate(glm::mat4(1.0f), glm::vec3(-camerax + temp_sprites[id].xpos, -cameray + temp_sprites[id].ypos, temp_sprites[id].zindex));

我一直在尝试如何将像素坐标转换为opengl坐标,以便在游戏中使用鼠标进行某些操作,我尝试了许多操作,但每次都失败了,下面是我的代码:

glm::mat4 anim;

glm::mat4 model;

model = glm::translate(glm::mat4(1.0f), glm::vec3(-camerax + temp_sprites[id].xpos, -cameray + temp_sprites[id].ypos, temp_sprites[id].zindex));


anim = glm::rotate(glm::mat4(1.0f), glm::radians(0.0f), axis_y);

model *= glm::scale(glm::mat4(1.0f), glm::vec3(temp_sprites[id].width, temp_sprites[id].height, 0.0f));


glm::mat4 projection = glm::ortho(-50.0f * gaspect, 50.0f * gaspect, -50.0f, 50.0f, -1.0f, 1.0f);

mvp = projection * model * anim;


glUniformMatrix4fv(uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp));

您需要知道
surfaceWidth
surfaceHeight
中曲面的宽度和高度(以像素为单位),以及
topLeftX
topLeftY
中左上角的像素坐标(如果不为零)

根据您的ortho调用,边界如下所示:

float left = -50.0f * gaspect;
float right = 50.0f * gaspect;
float bottom = -50.0f;
float top = 50.0f;
如果你有一个像素坐标
mouseX
mouseY
,减去左上角,然后像这样计算GL坐标:

float x = (((mouseX - topLeftX) / surfaceWidth) * (right - left)) + left;
float y = (((mouseY - topLeftY) / surfaceHeight) * (bottom - top)) + top;
这假设鼠标在屏幕下方增加(OpenGL坐标向上增加)


(这是一个身份模型转换)

这个问题很不清楚;也许可以在代码中添加一些注释,说明每个部分应该做什么。我关心的主要是glm::ortho行。如果像我在代码中一样有glm::ortho设置,我将如何转换坐标。看起来,我仍然无法让它工作。代码给出了这个公式中非常奇怪的值。我用的公式对吗?这是我的代码:float xx=((x-0)/640)*(右-左))+左;浮动yy=((y-0)/480)*(底部-顶部))+顶部;你到底是如何使用坐标的?你在那个位置画模型吗?该公式不考虑模型和动画矩阵,因此除了将模型简单地转换到该位置外,如果应用其他变换,它将不起作用,正如我在上一个注释中提到的。这只是取消正交矩阵的投影。看看glm的非项目功能: