I’m new to OpenGL, I only know the basic concepts. I have a bunch of coordinates which renders for example a triangle. I can query my cursor positions, but I cannot check whether it’s in the triangle or not. It requires some formulas, which I would have to rewrite if I had an rectangle or other objects. What is the simplest way to check if I clicked on a 2D object in OpenGL? Thanks in advance!

@Batyu,

Take a look at the dot-product and what it does.

For a regular polygon, you can check if dot() has same sign for all points … where each point is first in

- a vector to next point
- a vector to the cursor

… it’s worse if the polygon is not regular.

This is how I recall it. If it’s not proper, you’ll still find inspiration in the dot()

…

Looking at my code it’s composed of ‘mysterious’ [probably a signed distance] values that I call

`dist-sign-value(p1, p2, cursor)`

. I don’t think that the value in itself is any good, but if regular polygon-points has values of same sign the lines between points has the cursor on the same side.

`double dist_sign_value =`

` (p1.y - p2.y)*cursor.x`

` + (p2.x - p1.x)*cursor.y`

` + p1.x * p2.y - p2.x * p1.y`

@Batyu, the key fun of opengl is fiddeling with this grammar-school geometry. Don’t miss the chance.

The concept is called “picking”, and there are two basic approaches: geometric and rasterisation. The geometric approach involves performing a ray-triangle intersection for each triangle. Rasterisation involves rendering the scene, writing object IDs to the framebuffer instead of colours. In “legacy” OpenGL, there is another option: `glRenderMode(GL_SELECT)`

.

For the geometric approach, it’s common to use a simplified bounding volume (sphere, box or convex polyhedron) to efficiently eliminate objects, and only check individual triangles if the ray intersects the bounding volume.

For these two reasons, I prefer a single input script that handles input events and delegates them to the *objects* being *clicked*.