java - 确定与椭圆形的交点

标签 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");
    }
}

obstaclesShape 是椭圆形的 ArrayList。

Shape oval = new Ellipse2D.Double(getRandomX(), getRandomY(), obstacle.getRandomWidth(), obstacle.
this.obstaclesShape.add(oval);

但是使用这种方法不够可靠。该事件似乎几乎是随机触发的。

所以我问自己,使用数学来确定省略号边框的位置不是更好吗?我猜这将由角度和高度/宽度决定。

enter image description here

问题是如何准确地确定它?它的公式是什么?或者有更好的办法吗?

最佳答案

是的,值得应用一些数学来确定椭圆是否与矩形相交。

设矩形有角 (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

现在我们可以申请described here approach找到原点(圆心)和矩形之间的距离。如果它小于 1,对象就会相交。

稍微修改的功能(Delphi)

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;

关于java - 确定与椭圆形的交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901359/

相关文章:

java - Drools 在迭代时访问 HashMap 中的对象

java - 更改 eclipse 启动画面

java - 为什么(我的)Java 比 C++ 快 25 倍?

math - Windows 批处理文件数学怪异

iphone - 在 Objective-C 中四舍五入到 (1, 2, or 5) x 10^n?

java - 根据点偏移计算方向

java - 如何使用 Spring 创建动态菜单

javascript - 用 d3 中的 x 和 y 坐标绘制 tan 波

python - 列表列表 vs 字典

java - 类未找到 com.mysql.jdbc.Driver 异常