Java 确定与椭圆形状的交点
我正在使用Java,我正在尝试检测椭圆与矩形的交点 我认为首先使用Intersect就足够了:Java 确定与椭圆形状的交点,java,math,Java,Math,我正在使用Java,我正在尝试检测椭圆与矩形的交点 我认为首先使用Intersect就足够了: Shape rect = new Rectangle2D.Double(ant.getPosX(), ant.getPosY(), 5, 5); for (Shape obstacle : obstaclesShape) { if(obstacle.intersects(rect.getBounds())){ System.out.println("Boom"); }
Shape rect = new Rectangle2D.Double(ant.getPosX(), ant.getPosY(), 5, 5);
for (Shape obstacle : obstaclesShape) {
if(obstacle.intersects(rect.getBounds())){
System.out.println("Boom");
}
}
ObstacleShape是椭圆形的数组列表
Shape oval = new Ellipse2D.Double(getRandomX(), getRandomY(), obstacle.getRandomWidth(), obstacle.
this.obstaclesShape.add(oval);
但使用这种方法是不够可靠的。这一事件似乎几乎是随机触发的
所以我问自己,用数学来确定省略号边界的位置不是更好吗?我想这是由角度和高度/宽度决定的
问题是如何精确地确定它?它的公式是什么?或者有更好的方法吗?是的,值得应用一些数学知识,找出椭圆是否与矩形相交 假设矩形有角(x0,y0)和(x1,y1),椭圆有中心(cx,cy),水平半轴
a
,垂直扫描电镜轴b
首先,我们可以进行仿射变换以简化计算-我们将椭圆变换为以原点为中心的半径为1的圆。矩形也会变换,相交事实不会改变
With such transform we apply shift by (-cx,-cy), scaling by `1/a` in OX direction and scaling by `1/b` in 0Y direction. After that rectangle will have coordinates
xxx0 = (x0-cx) / a
yyy0 = (y0-cy) / b
xxx1 = (x1-cx) / a
yyy1 = (y1-cy) / b
现在我们可以应用它来查找原点(圆心)和矩形之间的距离。如果小于1,则对象确实相交
稍加修改的函数(Delphi)
函数rectdancetozerolessthan1(RR:TRect):布尔;
变量
wh,hh,dx,dy,t,squaredist:Double;
开始
平方列表:=0;
//宽度和高度
wh:=右后-左后;
hh:=RR.Bottom-RR.Top;
//双矩形中心坐标
dx:=-(右后左+右后右);
dy:=-(右上+右下);
//矩形边将平面分成9个部分,
t:=dx+wh;
如果t<0,则
平方列表:=t*t
否则开始
t:=dx-wh;
如果t>0,则
平方列表:=t*t
结束;
t:=dy+hh;
如果t<0,则
squaredist:=squaredist+t*t
否则开始
t:=dy-hh;
如果t>0,则
squaredist:=squaredist+t*t
结束;
结果=squaredist你能澄清所附图片吗?我有一个椭圆形,我知道形状中心的位置和右角点中心的位置。我知道椭圆形的高度和宽度,我想确定红色边框的位置@Xentros和您显示的内容看起来像是google上首次随机点击的“计算椭圆点”“我承认在将其转换为其他位置的点位置时遇到问题”“很可能您不应该在视图层中使用显示坐标。您应该使用自己的“障碍物”对象类型创建自己的坐标系,以进行碰撞检测。见此:
function RectDistanceToZeroLessThan1(RR: TRect): Boolean;
var
wh, hh, dx, dy, t, SquaredDist: Double;
begin
SquaredDist := 0;
//width and height
wh := RR.Right - RR.Left;
hh := RR.Bottom - RR.Top;
//doubled rectangle center coordinates
dx := - (RR.Left + RR.Right);
dy := - (RR.Top + RR.Bottom);
//rectangle sides divide plane to 9 parts,
t := dx + wh;
if t < 0 then
SquaredDist := t * t
else begin
t := dx - wh;
if t > 0 then
SquaredDist := t * t
end;
t := dy + hh;
if t < 0 then
SquaredDist := SquaredDist + t * t
else begin
t := dy - hh;
if t > 0 then
SquaredDist := SquaredDist + t * t
end;
Result = SquaredDist <= 4 // due to removed 0.5 coefficients
end;