# simple way to determine what object a mouse is pointed over? (OpenGL, freeglut, c++)

I know how to make actions happen based on if the mouse is being clicked or released and if the mouse is in motion or being clicked and in motion (all using freeglut).

But google has me very stressed with options on which way I should use to determine what object is being clicked.

Can someone please show me the simplest way you can think of to determine what object is being clicked so I can move that object independently using the glut functions?

As we are working with 2D objects, an object is pointed at if the position of the mouse is inside the object. This notion of being inside differs for different geometric shapes.

For a rectangle width upper left corner `c` and `width`, `height` the the function could look like:

``````bool isInsideRectangle(double x, double y) {
// The mouse is inside if the coordinates are 'inside' all walls
return (x > c.x &&
y > c.y &&
x < c.x + width &&
y < c.y + height);
}
``````

For a circle with center `c` and radius `r`, it could look like this:

``````bool isInsideCircle(double x, double y) {
// The mouse is inside if the distance to the center of the circle
// is less than the radius
return std::sqrt((x - c.x)*(x - c.x) + (y - c.y)*(y - c.y)) < r;
}
``````

For another shape you would have to figure out another function for how to calculate if a mouse position is inside or not, however in many cases you can simplify it to a bounding rectangle or sphere.

Regardless of whether you're working with 2D or 3D by far the simplest solution is to assign each pickable object a unique colour, which isn't normally used at all. Then for every click event you render (to the back buffer) the same scene with the unique colour applied to each object. By disabling lighting etc. the problem then becomes one of looking at the pixel color under the mouse and using a lookup table to see which object was clicked.

Even in 16 bit colour depth that still gets you 2^16 unique pickable objects and in reality that's rare in modern application to have less than 2^24.