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

How do I convert pixel coordinates to opengl coordinates In my 2d game that uses glm::ortho?

本文关键字:坐标 opengl 像素 转换 游戏 glm ortho 2d      更新时间:2023-10-16

我一直在想如何将像素坐标转换为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));

您需要知道surfaceWidthsurfaceHeight中曲面的宽度和高度(以像素为单位(,以及topLeftXtopLeftY中左上角的像素坐标(如果不是零(。

根据你的正交调用,边界如下:

float left = -50.0f * gaspect;
float right = 50.0f * gaspect;
float bottom = -50.0f;
float top = 50.0f;

如果你有一个像素坐标mouseXmouseY,减去左上角,然后像这样计算GL坐标:

float x = (((mouseX - topLeftX) / surfaceWidth) * (right - left)) + left;
float y = (((mouseY - topLeftY) / surfaceHeight) * (bottom - top)) + top;

这假设鼠标Y在屏幕下方增加(OpenGL坐标在屏幕上方增加(。

(这是用于身份模型转换(