2017-07-04 2 views
1

私はJavaで作業しており、卵形と長方形の交差を検出しようとしています。卵形との交差を特定する

Iタフで最初に十分であろう交差を使用して:

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_ )) – xenteros

答えて

1

はい、数学を適用し、楕円が矩形と交差するかどうかを調べる価値があります。

矩形のコーナー(x0、y0)と(x1、y1)、楕円の中心(cx、cy)、水平セミ軸a、垂直セミ軸bとします。

まずは計算を簡素化するためにアフィン変換を行うことができます - 私たちは、半径1 Rectangleがあまりにも変えていく、との交差点の事実は変更されませんと、原点を中心としたに楕円を変換します。

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未満の場合、オブジェクトは交差します。

わずかに変更された機能(デルファイ)

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;