如何从 GLUT 坐标转换为窗口坐标

How to convert from GLUT coordinates to window coordinates

本文关键字:坐标 转换 窗口 GLUT      更新时间:2023-10-16

可能的重复项:
过剩鼠标坐标

假设我有一个 600x600 的窗口。
当我收到鼠标事件时,我不知道鼠标的真实位置是什么,在 OpenGL 中,我使用它来绘制点:

(-0.5,0.5) | (0.5,0.5)
           |
 --------(0,0)-------
           |
           |
(-0.5,-0.5) | (0.5,-0.5)

但是当我收到取决于窗口大小的 GLUT 鼠标事件时,我会得到不同的坐标。我想要一个相对(到窗口)坐标系。我怎么得到这个?

我很确定 glut 会给你窗口空间中的鼠标坐标(即,如果窗口是 800x600 并且鼠标位置在中间,它会给你 x:400, y: 300),所以如果你想把它带到你上面发布的 opengl 空间,你会执行以下操作:

float x = (400 / 800) - 0.5f; //0.0
float y = (300 / 600) - 0.5f; //0.0

所以通用版本看起来像这样:

float mouseX = (theGlutMouseXCoordinate / theGlutWindowWidth) - 0.5f;
float mouseY = (theGlutMouseYCoordinate / theGlutWindowHeight) - 0.5f;

也许我误读了你的问题,或者过度简化了答案,但你不只是在寻找这样的东西吗:

float x = mouse.x / screen.width;  //x now in [0,1]
float y = mouse.y / screen.height; //y now in [0,1]
x-=0.5f;
y-=0.5f;

或颠倒:

float wx = (x + 0.5f) * screen.width;
float wy = (Y + 0.5f) * screen.height;