tripleblep
tripleblep

Reputation: 540

Check if point is in circular sector

I found this question that deals with the same issue. The provided answers work, but I need to change it slightly for my case. Below is the answer I went with:

double theta = Math.atan2(pointerY - height / 2, pointerX - width / 2);

if(theta<0)
    theta = Math.PI - theta;
int whichSlice = 0;
double sliceSize = Math.PI*2 / 4;
double sliceStart;

for(int i=1; i<=4; i++) {
    sliceStart = i*sliceSize;
    if(theta < sliceStart) {
        whichSlice = i;
        break;
    }
}

In my case, I need to rotate the quadrants by 45 degrees. Below is an example; red is what this code does, while green is what I want:

enter image description here

I've tried various code alterations, but still can't figure it out.

Upvotes: 1

Views: 1229

Answers (1)

Dean Leitersdorf
Dean Leitersdorf

Reputation: 1341

EDIT:

First off, create your circle in it's own desperate JComponent, and add it's own listeners - basically create a class for this circle, make the circle itself receive mouse events, and MAKE SURE THAT THE CIRCLE OCCUPIES THE ENTIRE RECTANGLE OF THE JCOMPONENT - it must be touching all edges (I will be using this.getHeight() and this must return the height of the bounding box of the circle)!!!

Fixed code below to support such a case, in addition to support y axis which increases downwards:

Step 1: Check if we are inside the circle. Step 2: Check if we are above/below the diagonal lines (note: equations for diagonal lines are y = x, and y = -x)

Point pointWeAreChecking;
Point centerOfCircle;
double radius;




if(Math.pow(Math.pow(pointWeAreChecking.x-centerOfCircle.x , 2) + Math.pow(pointWeAreChecking.y-centerOfCircle.y , 2), 0.5) <= radius)
{
//Means we are in circle.
if(pointWeAreChecking.y>pointWeAreChecking.x)
{
//Means it is either in 2 or 3 (it is below y = -x line)
if(pointWeAreChecking.y>-pointWeAreChecking.x + this.getHeight()){
//We are in 2.
}else
{
//We are in 3.    
}
}else
{
if(pointWeAreChecking.y>-pointWeAreChecking.x + this.getHeight())
{
//We are in 4.
}else
{
//We are in 2.
}
}

 }

Upvotes: 1

Related Questions