2017-07-04 48 views
1

我正在使用Java,我正在嘗試檢測橢圓與矩形的交集。確定與Ovale形狀的交集

我韌起初使用相交就足夠了:

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

的事情是如何精確地確定了嗎?它的公式是什麼?或者,還有更好的方法?

+0

你能澄清的圖片附? – xenteros

+0

我有一個橢圓形的形狀,我知道形狀的中心位置和右中心點的中心位置。我知道橢圓的高度和寬度,我想確定紅色邊框的位置。 @xenteros –

+0

[這是橢圓形](https://en.wikipedia.org/wiki/Oval)和你展示的東西看起來像一個隨機的[危險](https://en.wikipedia.org/wiki/Hazard_(golf )) – xenteros

回答

1

是的,值得應用一些數學算法,並找出你的橢圓是否與矩形相交。

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