First dog watch, 3 bells (5:44 pm)

Today I went to one of our resident math geniuses for a trig lesson. Yes, trig—that thing you swore in high school was stupid and you'd never use it again.

The problem was I'm drawing a pie chart and needed to find when the mouse was inside any one of the wedges.

So here's how you find whether a mouse click was inside a wedge of a pie chart:

Given that the circle is inscribed in a bounding box 200x200 pixels and a mouse click happened at (130,50), here's how you check it:

First, check the distance from the center of the circle to the click coordinates. If this distance is greater than the radius of the circle, you need not go any further. This part was easy and I remembered it from high school.

The center of the circle lies at (100, 100). The distance of the click at (130, 50) is:

`sqrt((130-100)^2 + (50-100)^2)`

, or the square root of the square of the difference between the x-coordinates plus the square of the difference between the y-coordinates. If this value is greater than 100 (the radius of our circle), the click is outside the circle and no more math is required.

Next comes the tricky part. If the click was inside the circle, you need to find the angle of the click. In the diagram, you should know angles `a, b, c, `

and `d`

because you already drew them. Depending on your API, you may have them in degrees, or sixteenths of degrees like I did.

So you start by normalizing the `x`

and `y`

coordinates. This means translate it to `(0, 0)`

, or more simply *subtract the x and y value of the center from the x and y value of the click*. In my case this means my translated-x (`tx`

) and translated-y (`ty`

) are **(30, -50)** (130-100 and 50-100).

The tangent of the angle θ is the opposite over the adjacent side, which are your translated x and y coordinates. To find the angle you need to use `tan`^{-1} ty / tx

, or `atan(ty/tx)`

if you include *cmath*. This result is in **radians**. Make sure `tx`

is non-zero or you will have some problems here.

This part is important! If `tx`

was negative, you must add π to the radians to make sure you get the angle into the negative-x side of the graph! If you don't do this you'll have even more problems.

To convert θ to degrees, multiply the radians by `180 / π`

.

In my API (I'm using Qt), the degrees go in the opposite direction, so I had to invert the angle.

Compare this result to angles `a-d`

and you have your wedge!

*Related*

### Leave a Reply