c - 当正交设置为 -1.0 到 1.0 时获取鼠标位置

标签 c opengl glut freeglut

我是使用 c 的 OpenGL/GLUT 新手。我想实现一个当用户单击它时有回调的按钮。为了更好地理解这一点,我有一个简单的程序,可以在单击鼠标的位置绘制一个点。 这是代码

#include <freeglut.h>
GLint   mousePressed = 0;
GLfloat mouseX, mouseY;
GLint windowHieght = 400;
GLint windowWidth = 500; 

void myDisplay()
{
    glClear(GL_COLOR_BUFFER_BIT);

    if (mousePressed)
    {
        // draw the dot
        glBegin(GL_POINTS);

        // draw the vertex at that point
        glVertex2f(mouseX, mouseY);

        glEnd();
    }

    glFlush();
}
void myMouseButton(int button, int state, int x, int y)
{
    if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
        exit(0);

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        mousePressed = 1;

        mouseX = (GLfloat)x / (GLfloat)windowWidth;

        mouseY = (GLfloat)windowHieght - (GLfloat)y;  
        mouseY = mouseY / (GLfloat)windowHieght;

        glutPostRedisplay();
    }
void main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB);
    glutInitWindowSize(windowWidth, windowHieght);
    glutInitWindowPosition(100, 150);
    glutCreateWindow("dots");
        gluOrtho2D(0.0, 1.0, 0.0, 1.0);
    glutDisplayFunc(myDisplay);
    glutMouseFunc(myMouseButton);

    initializeGL();

    glutMainLoop();
}

一切都按预期工作,但是当我将正交更改为 (-1.0,1.0,-1.0,1.0) 时,我没有得到相同的结果。我怎样才能获得相同的行为?

最佳答案

您的 myMouseButton 函数依赖于两个轴上的正交投影均为 0-1。既然你已经改变了这一点,你也需要改变这个函数中的数学。

简单来说,新的正交坐标范围可以被视为旧范围缩放 2,然后减去 1...

[0, 1] * 2 - [1, 1] => [-1, 1]

因此,您只需对现有的鼠标坐标方程执行相同的操作即可。

mouseX = mouseX * 2.0f - 1.0f;
mouseY = mouseY * 2.0f - 1.0f;

关于c - 当正交设置为 -1.0 到 1.0 时获取鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64274911/

相关文章:

c++ - 仅当使用 opengl 3.2 上下文或更高版本时,glVertexAttribPointer 和 glDrawArrays 的 GL_ERROR == 1282

c++ - 在 openGL 4 中呈现文本 - 不起作用

c++ - 如何通过鼠标单击获取相对的 x 和 y 位置

c - 理解C中的scanf()(段错误)

c - 在 C 中使用 3D-Array 时出现内存读取异常

unix中的清除提示

c++ - 这是什么控制风格?

opengl - 在MFC中的OpenGL上下文上方绘制文本

opengl - 使用 OpenGL 和 GLSL 的 SSAO 算法出现奇怪的性能行为

c++ - OpenGL 透视图看起来不对