如何在拖动绘制的矩形时保持鼠标位置成比例?

问题描述

我当前正在创建可以使用OpenGL选择和拖动的框。现在,我遇到一个问题,当我单击一个框时,它会将鼠标捕捉到中心并将框从中心点拖动。我希望将框从鼠标单击的位置而不是中心拖动。

这是我移动鼠标时调用的appMotionFunc。第10行和第11行使鼠标居中。我无法弄清楚如何通过修改这些行正确地使它成比例。坐标(0,0)位于框的左上方,它向右绘制宽度,向下方绘制高度。

    void appMotionFunc(int x,int y) {
    // Convert from Window to Scene coordinates
    float mx = (float)x;
    float my = (float)y;

    windowToScene(mx,my);

    // Your code here...
    if(rects[0]->selected){
        rects[0]->x = mx - rects[0]->w/2;
        rects[0]->y = my + rects[0]->h/2;
    }
    // Again,we redraw the scene
    glutPostRedisplay();
}

这是绘制矩形的函数的外观。

void Rect::draw(){

    if (selected){

        glColor3f(1,1,1);
        glBegin(GL_LInes);

        glVertex3f(x,y,0.1);
        glVertex3f(x+w,0.1);

        glVertex3f(x+w,y-h,0.1);
        
        glVertex3f(x+w,0.1);
        glVertex3f(x,0.1);
        
        glVertex3f(x,0.1);

        glEnd();
        
        glColor3f(red,green,blue);

        glBegin(GL_polyGON);

        glVertex3f(x,0.1);

        glEnd();

        
    }
    else{
        glColor3f(red,blue);

        glBegin(GL_polyGON);

        glVertex2f(x,y);
        glVertex2f(x+w,y-h);
        glVertex2f(x,y-h);

        glEnd();
    }
}

如果无法提供足够完整的上下文来解决问题,我将提供程序的更多部分,但是我认为这是所有相关的代码

解决方法

我在这些行上讨论的增量仅需要每次鼠标单击一次计算,而不是每次移动鼠标一次。一个简单的错误使我花了很长时间才弄清楚。