鼠标按下投影 (C++ OpenGL)

mouse press projection (c++ openGL)

本文关键字:C++ OpenGL 投影 鼠标      更新时间:2023-10-16

我正在用openGL制作一个简单的教程游戏,并对触摸方法有疑问。请查看我的代码:

我的 (0,0) 点位于屏幕中央:

void Init()
{
    glClearColor(0.3,0.3,0.3,0.0);
    glMatrixMode(GL_PROJECTION);
    glOrtho(-400.0,400.0,-300.0,300.0,0,1.0); //сетка, середина в точке 0
}

在此之前,我调用鼠标方法:

glutPassiveMotionFunc(Mouse);
glutMouseFunc(MousePress);

在方法中 鼠标按下 当触摸即将到来时,它是另一个系统坐标,屏幕左上角的 (0,0) 点。请您告诉我更好的方法,然后在鼠标按方法中制作类似 x-300;y-400 的东西。

鉴于正交投影更简单,您的"x-300;y-400"是正确的方法,尽管您可能也想进行一些缩放......

float x = mouseX/(float)windowWidth;
float y = 1.0f - mouseY/(float)windowHeight; //flip since y=0 is at the top
//x and y are now 0 to 1, bottom left to top right
x = left + x * (right - left);
y = bottom + y * (top - bottom);
//x and y are now in 3D coordinates

在这里,左/右/下/上来自 glOrtho,在您的情况下可以按如下方式替换(但当然存储在变量中更好)......

x = -400 + x * (400 - (-400));
y = -300 + y * (300 - (-300));

如果您使用的是透视投影,它会变得有点复杂,正如我在这里所描述的。

[编辑]
假设窗口大小为 800x600,则上述取消为 {x-400,300-y} 。例如

mouseY = 50;
windowHeight = 600;
float y = 1.0f - (50/(float)600); //1.0 - 0.08333 = 0.91667
y = -300 + y * (300 - (-300)); //-300 + 0.91667 * 600 = 250, also 300-50