【问题标题】:Getting the mouse position when ortho is set from -1.0 to 1.0当正交设置从 -1.0 到 1.0 时获取鼠标位置
【发布时间】:2021-01-24 05:34:14
【问题描述】:

我是使用 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) 时,我没有得到相同的结果。我怎样才能获得相同的行为?

【问题讨论】:

    标签: c opengl glut freeglut


    【解决方案1】:

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

    简而言之,您的新正交坐标范围可以被认为是按 2 缩放的旧范围,然后减去 1...

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

    所以你只需要对现有的鼠标坐标方程做同样的事情。

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

    【讨论】:

      猜你喜欢
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多