Search code examples
c++openglgraphicsmouseeventpixel

How do I check if the user pressed any part of the circle?


I have noticed that the mouse control coordinates are different then that of the coordinates of drawing on openGl. Is this true?

I am trying to determine if the user pressed inside the circle, however when I implement my distance formula to the center of the circle, if becomes extremely large. How do I check if the user pressed any part of the circle?

plate_scale is the radius of the circle. 

distance method

float mouseDistancefromCenterofCircle(double mouseX, double mouseY, double circleX, double circleY)
{
    double distance;
    distance = sqrt((mouseX - circleX)*(mouseX - circleX) + (mouseY - circleY)*(mouseY - circleY));
    return distance;
}

mouse code

void mouseControl1(int button, int state, int x, int y)
{
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        if (mouseDistancefromCenterofCircle(x, y, centerX, centerY) <= plate_scale)
        {
            plate_translate_X = x;
            plate_translate_Z = y;
        }
    }
    glutPostRedisplay();
}

Solution

  • There is nothing wrong with the length of your distance formula. If you want more simplicity, create a simple class for the circle:

    class Circle
    {
    private:
        double centerX;
        double centerY;
        double plate_scale; //or simply "radius"
    
    public:
        //a reasonable constructor
        bool includes (double mouseX, double mouseY) //the actual implementation in a cpp file
        {
             return sqrt((mouseX - centerX)*(mouseX - centerX) + (mouseY - centerY)*(mouseY - centerY)) <= plate_scale;
        }
    };
    

    The usage would be pretty easy to read and understand:

    Circle someCircle (19.0, 16.0, 5.0);
    //...
    if (someCircle.includes(x, y))
    {
        plate_translate_X = x;
        plate_translate_Z = y;
    }