How to keep mouse position proportional while dragging a drawn rectangle?

129 views Asked by At

I am currently creating boxes that you can select and drag around using OpenGL. Right now I am having the issue where when I click on a box, it snaps the mouse to the center and drags the box from the center point. I want to have the boxes be dragged from the point where the mouse clicked instead of the center.

This is the appMotionFunc called when I move my mouse. Lines 10 and 11 are what keep my mouse centered. I can't figure out how to get it to proportion correctly by modifying those lines though. Coordinates (0,0) are in the top left of the box and it draws the width to the right and the height down.

    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();
}

This is how the function drawing the rectangles looks.

void Rect::draw(){

    if (selected){

        glColor3f(1,1,1);
        glBegin(GL_LINES);

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

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

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

        glBegin(GL_POLYGON);

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

        glEnd();

        
    }
    else{
        glColor3f(red, green, blue);

        glBegin(GL_POLYGON);

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

        glEnd();
    }
}

I will provide more parts of the program if this doesn't provide a full enough context to solve the problem, but I think this is all the relevant code.

1

There are 1 answers

0
Austin Near On

The delta I was talking about on those lines needs to be only calculated once per mouse click instead of every time you move the mouse. Simple error that took me too long to figure out.