java 点是否在圆内,Java - 如何检查一个点是否在一个圆圈内

I have a circle drawn, and I want to make it so I can have more slices than four. I can easily do four quadrants because I just check if the mouse in in the circle and inside a box.

This is how I am checking if the point is in the circle.

if( Math.sqrt((xx-x)*(xx-x) + (yy-y)*(yy-y)) <= radius)

{

return true;

}

else

{

return false;

}

How can I modify this if the circle is divided into more than 4 regions?

解决方案

First we can check that the point is within the circle as you did. But I woudln't combine this with a check for which quadrant (is that why you have radius/2 ?)

if( (xx-x)*(xx-x) + (yy-y)*(yy-y) > radius*radius)

return false;

Now we can look to see which region the point is in by using the atan2 function. atan2 is like Arctan except the Arctangent function always returns a value between -pi/2 and pi/2 (-90 and +90 degrees). We need the actual angle in polar coordinate fashion. Now assuming that (x,y) is the center of your circle and we are interested in the location of the point (xx,yy) we have

double theta = Math.atan2(yy-y,xx-x);

//theta is now in the range -Math.PI to Math.PI

if(theta<0)

theta = Math.PI - theta;

//Now theta is in the range [0, 2*pi]

//Use this value to determine which slice of the circle the point resides in.

//For example:

int numSlices = 8;

int whichSlice = 0;

double sliceSize = Math.PI*2 / numSlices;

double sliceStart;

for(int i=1; i<=numSlices; i++) {

sliceStart = i*sliceSize;

if(theta < sliceStart) {

whichSlice = i;

break;

}

}

//whichSlice should now be a number from 1 to 8 representing which part of the circle

// the point is in, where the slices are numbered 1 to numSlices starting with

// the right middle (positive x-axis if the center is (0,0).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值