質問

2Dユークリッド空間で円と長方形が交差するかどうかを確認するにはどうすればよいですか? (つまり、古典的な2Dジオメトリ)

役に立ちましたか?

解決

円が長方形と交差するのは2つの場合のみです:

  • 円の中心が長方形の内側にあるか、
  • 長方形の端の1つに円内の点があります。

これは、長方形が軸平行である必要がないことに注意してください。

円と長方形が交差するさまざまな方法

(これを確認する1つの方法:すべてのエッジが円内に点を持たない場合(すべてのエッジが完全に「外側」である場合)、円がポリゴンと交差する唯一の方法は、完全にポリゴンの内側にあります。)

その洞察により、円の中心は P で半径は R で、長方形の頂点は A B C D の順に(完全なコードではない):

def intersect(Circle(P, R), Rectangle(A, B, C, D)):
    S = Circle(P, R)
    return (pointInRectangle(P, Rectangle(A, B, C, D)) or
            intersectCircle(S, (A, B)) or
            intersectCircle(S, (B, C)) or
            intersectCircle(S, (C, D)) or
            intersectCircle(S, (D, A)))

ジオメトリを記述している場合は、おそらく上記の関数がライブラリにすでに存在しています。それ以外の場合、 pointInRectangle()はいくつかの方法で実装できます。一般的なポリゴン内のポイントメソッドはすべて機能しますが、長方形の場合はこれを確認するだけです動作:

0 ≤ AP·AB ≤ AB·AB and 0 ≤ AP·AD ≤ AD·AD

そして intersectCircle()も簡単に実装できます。1つの方法は、 P からラインまでの垂線の足が十分に近く、それ以外の場合はエンドポイントを確認します。

クールなことは、同じというアイデアは長方形だけでなく、円と単純なポリゴン—凸面である必要はありません!

他のヒント

ここに私がそれをする方法があります:

bool intersects(CircleType circle, RectType rect)
{
    circleDistance.x = abs(circle.x - rect.x);
    circleDistance.y = abs(circle.y - rect.y);

    if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
    if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }

    if (circleDistance.x <= (rect.width/2)) { return true; } 
    if (circleDistance.y <= (rect.height/2)) { return true; }

    cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
                         (circleDistance.y - rect.height/2)^2;

    return (cornerDistance_sq <= (circle.r^2));
}

仕組みは次のとおりです。

illusration

  1. 最初のペアの線は、円の中心と長方形の中心の間のxとyの差の絶対値を計算します。これにより、4つの象限が1つに集約されるため、計算を4回行う必要がなくなります。この画像は、円の中心が存在する領域を示しています。単一の象限のみが示されていることに注意してください。長方形は灰色の領域であり、赤い境界線は、長方形の端からちょうど1半径離れた重要な領域の輪郭を示します。交差点が発生するには、円の中心がこの赤い境界線内になければなりません。

  2. 2番目の線のペアは、円が長方形から(どちらの方向でも)十分に離れており、交差が不可能な簡単なケースを排除します。これは、画像の緑色の領域に対応しています。

  3. 線の3番目のペアは、円が(どちらの方向でも)長方形に十分近く、交差が保証される簡単なケースを処理します。これは、画像のオレンジとグレーのセクションに対応しています。ロジックを理解するために、この手順は手順2の後に行う必要があることに注意してください。

  4. 残りの線は、円が長方形の角と交差する可能性がある難しいケースを計算します。解決するには、円の中心と角からの距離を計算し、距離が円の半径以下であることを確認します。この計算は、中心が赤の網掛け領域内にあるすべての円に対してfalseを返し、中心が白の網掛け領域内にあるすべての円に対してtrueを返します。

これは、実装が非常に簡単な(そして非常に高速な)別のソリューションです。球体が長方形に完全に入ったときを含む、すべての交差点をキャッチします。

// clamp(value, min, max) - limits value to the range min..max

// Find the closest point to the circle within the rectangle
float closestX = clamp(circle.X, rectangle.Left, rectangle.Right);
float closestY = clamp(circle.Y, rectangle.Top, rectangle.Bottom);

// Calculate the distance between the circle's center and this closest point
float distanceX = circle.X - closestX;
float distanceY = circle.Y - closestY;

// If the distance is less than the circle's radius, an intersection occurs
float distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
return distanceSquared < (circle.Radius * circle.Radius);

適切な数学ライブラリを使用すると、3行または4行に短縮できます。

球体と長方形がIIFを交差
円の中心と四角形の1つの頂点の間の距離は、球体の半径よりも小さい
または
円の中心と四角形の1つの端の間の距離は、球の半径よりも小さい([ポイントライン距離])
または
円の中心は四角形の内側にあります

ポイント間距離:

P1 = [x1,y1]
P2 = [x2,y2]
Distance = sqrt(abs(x1 - x2)+abs(y1-y2))

ポイントライン距離:

L1 = [x1,y1],L2 = [x2,y2] (two points of your line, ie the vertex points)
P1 = [px,py] some point

Distance d =  abs( (x2-x1)(y1-py)-(x1-px)(y2-y1) ) / Distance(L1,L2)


四角形の内側の円の中心:
分離軸アプローチを取る:点から長方形を分離する線への投影が存在する場合、それらは交差しません

長方形の辺に平行な線上に点を投影すると、それらが交差するかどうかを簡単に判断できます。 4つのすべての投影で交差しない場合、それら(点と長方形)は交差できません。

必要なのは内積(x = [x1、x2]、y = [y1、y2]、x * y = x1 * y1 + x2 * y2)

テストは次のようになります。

//rectangle edges: TL (top left), TR (top right), BL (bottom left), BR (bottom right)
//point to test: POI

seperated = false
for egde in { {TL,TR}, {BL,BR}, {TL,BL},{TR-BR} }:  // the edges
    D = edge[0] - edge[1]
    innerProd =  D * POI
    Interval_min = min(D*edge[0],D*edge[1])
    Interval_max = max(D*edge[0],D*edge[1])
    if not (  Interval_min ≤ innerProd ≤  Interval_max ) 
           seperated = true
           break  // end for loop 
    end if
end for
if (seperated is true)    
      return "no intersection"
else 
      return "intersection"
end if

これは軸に沿った長方形を想定しておらず、凸集合間の交差をテストするために簡単に拡張できます。

これは最速のソリューションです:

public static boolean intersect(Rectangle r, Circle c)
{
    float cx = Math.abs(c.x - r.x - r.halfWidth);
    float xDist = r.halfWidth + c.radius;
    if (cx > xDist)
        return false;
    float cy = Math.abs(c.y - r.y - r.halfHeight);
    float yDist = r.halfHeight + c.radius;
    if (cy > yDist)
        return false;
    if (cx <= r.halfWidth || cy <= r.halfHeight)
        return true;
    float xCornerDist = cx - r.halfWidth;
    float yCornerDist = cy - r.halfHeight;
    float xCornerDistSq = xCornerDist * xCornerDist;
    float yCornerDistSq = yCornerDist * yCornerDist;
    float maxCornerDistSq = c.radius * c.radius;
    return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
}

実行の順序に注意してください。幅/高さの半分は事前に計算されています。また、平方は「手動で」行われます。いくつかのクロックサイクルを節約します。

球体と軸が揃っていないボックスの間の衝突を解決するためのCコードを次に示します。それは私自身のいくつかのライブラリルーチンに依存していますが、一部の人にとっては役立つかもしれません。私はゲームでそれを使用していますが、完全に機能します。

float physicsProcessCollisionBetweenSelfAndActorRect(SPhysics *self, SPhysics *actor)
{
    float diff = 99999;

    SVector relative_position_of_circle = getDifference2DBetweenVectors(&self->worldPosition, &actor->worldPosition);
    rotateVector2DBy(&relative_position_of_circle, -actor->axis.angleZ); // This aligns the coord system so the rect becomes an AABB

    float x_clamped_within_rectangle = relative_position_of_circle.x;
    float y_clamped_within_rectangle = relative_position_of_circle.y;
    LIMIT(x_clamped_within_rectangle, actor->physicsRect.l, actor->physicsRect.r);
    LIMIT(y_clamped_within_rectangle, actor->physicsRect.b, actor->physicsRect.t);

    // Calculate the distance between the circle's center and this closest point
    float distance_to_nearest_edge_x = relative_position_of_circle.x - x_clamped_within_rectangle;
    float distance_to_nearest_edge_y = relative_position_of_circle.y - y_clamped_within_rectangle;

    // If the distance is less than the circle's radius, an intersection occurs
    float distance_sq_x = SQUARE(distance_to_nearest_edge_x);
    float distance_sq_y = SQUARE(distance_to_nearest_edge_y);
    float radius_sq = SQUARE(self->physicsRadius);
    if(distance_sq_x + distance_sq_y < radius_sq)   
    {
        float half_rect_w = (actor->physicsRect.r - actor->physicsRect.l) * 0.5f;
        float half_rect_h = (actor->physicsRect.t - actor->physicsRect.b) * 0.5f;

        CREATE_VECTOR(push_vector);         

        // If we're at one of the corners of this object, treat this as a circular/circular collision
        if(fabs(relative_position_of_circle.x) > half_rect_w && fabs(relative_position_of_circle.y) > half_rect_h)
        {
            SVector edges;
            if(relative_position_of_circle.x > 0) edges.x = half_rect_w; else edges.x = -half_rect_w;
            if(relative_position_of_circle.y > 0) edges.y = half_rect_h; else edges.y = -half_rect_h;   

            push_vector = relative_position_of_circle;
            moveVectorByInverseVector2D(&push_vector, &edges);

            // We now have the vector from the corner of the rect to the point.
            float delta_length = getVector2DMagnitude(&push_vector);
            float diff = self->physicsRadius - delta_length; // Find out how far away we are from our ideal distance

            // Normalise the vector
            push_vector.x /= delta_length;
            push_vector.y /= delta_length;
            scaleVector2DBy(&push_vector, diff); // Now multiply it by the difference
            push_vector.z = 0;
        }
        else // Nope - just bouncing against one of the edges
        {
            if(relative_position_of_circle.x > 0) // Ball is to the right
                push_vector.x = (half_rect_w + self->physicsRadius) - relative_position_of_circle.x;
            else
                push_vector.x = -((half_rect_w + self->physicsRadius) + relative_position_of_circle.x);

            if(relative_position_of_circle.y > 0) // Ball is above
                push_vector.y = (half_rect_h + self->physicsRadius) - relative_position_of_circle.y;
            else
                push_vector.y = -((half_rect_h + self->physicsRadius) + relative_position_of_circle.y);

            if(fabs(push_vector.x) < fabs(push_vector.y))
                push_vector.y = 0;
            else
                push_vector.x = 0;
        }

        diff = 0; // Cheat, since we don't do anything with the value anyway
        rotateVector2DBy(&push_vector, actor->axis.angleZ);
        SVector *from = &self->worldPosition;       
        moveVectorBy2D(from, push_vector.x, push_vector.y);
    }   
    return diff;
}

実際には、これははるかに簡単です。必要なものは2つだけです。

最初に、円の中心から長方形の各線までの4つの直交距離を見つける必要があります。そのうち3つが円の半径より大きい場合、円は長方形と交差しません。

次に、円の中心と長方形の中心の間の距離を見つける必要があり、距離が長方形の対角線の長さの半分より大きい場合、円は長方形の内側にはなりません。

がんばって!

私が思いついた最も簡単な解決策は非常に簡単です。

これは、円に最も近い長方形内のポイントを見つけ、距離を比較することで機能します。

これらのすべてをいくつかの操作で実行でき、sqrt関数を回避することもできます。

public boolean intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
{
   float closestX = (cx < left ? left : (cx > right ? right : cx));
   float closestY = (cy < top ? top : (cy > bottom ? bottom : cy));
   float dx = closestX - cx;
   float dy = closestY - cy;

   return ( dx * dx + dy * dy ) <= radius * radius;
}

これで終わりです!上記のソリューションでは、x軸が下向きの世界の左上に原点があることを想定しています。

移動する円と長方形の衝突を処理するソリューションが必要な場合、それははるかに複雑で、カバーされています私の別の答え。

視覚化するには、キーボードのテンキーを使用します。キー「5」が長方形を表す場合、すべてのキー1〜9は、長方形を構成する線で分割された9つの象限を表します(5が内側になります)。

1)円の中心が象限5(つまり、長方形の内側)にある場合、2つの形状は交差します。

それが邪魔にならないように、2つの可能なケースがあります。 a)円は、長方形の2つ以上の隣接するエッジと交差します。 b)円は長方形の1つのエッジと交差します。

最初のケースは簡単です。円が長方形の2つの隣接するエッジと交差する場合、それらの2つのエッジを接続するコーナーが含まれている必要があります。 (つまり、その中心は既に説明した象限5にあります。また、円が長方形の2つの対向するエッジのみと交差する場合も対象となります。)

2)長方形の角A、B、C、Dのいずれかが円の内側にある場合、2つの形状は交差します。

2番目のケースはより複雑です。円の中心が象限2、4、6、または8のいずれかにある場合にのみ発生することに注意してください(実際、中心が象限1、3、7、8のいずれかにある場合、対応するコーナーがそれに最も近いポイントになります。)

ここで、円の中心が「エッジ」象限のいずれかにあり、対応するエッジとのみ交差する場合があります。次に、円の中心に最も近いエッジ上のポイントは、円の内側になければなりません。

3)AB、BC、CD、DAの各線について、円の中心を通る垂直線p(AB、P)、p(BC、P)、p(CD、P)、p(DA、P)を作成しますP.各垂直線について、元のエッジとの交点が円の内側にある場合、2つの形状が交差します。

この最後のステップにはショートカットがあります。円の中心が象限8にあり、エッジABが上端である場合、交差点はAとBのy座標、および中心Pのx座標を持ちます。

4つの線の交点を構築し、それらが対応するエッジにあるかどうかを確認するか、どの象限Pが存在するかを調べて、対応する交点を確認します。どちらも同じブール式に簡略化する必要があります。上記のステップ2では、Pが「コーナー」象限の1つにあることを除外していなかったことに注意してください。交差点を探しただけです。

編集:実は、#2は上記の#3のサブケースであるという単純な事実を見落としていました。結局のところ、角もエッジ上のポイントです。すばらしい説明については、以下の@ShreevatsaRの回答を参照してください。一方で、迅速で冗長なチェックが必要な場合を除き、上記の#2を忘れてください。

この関数は、CircleとRectangle間の衝突(交差)を検出します。彼は答えでe.Jamesメソッドのように動作しますが、これは長方形のすべての角度(右上隅だけでなく)の衝突を検出します。

注:

aRect.origin.x aRect.origin.y は、長方形の左下の角度の座標です!

aCircle.x および aCircle.y は、サークルセンターの座標です!

static inline BOOL RectIntersectsCircle(CGRect aRect, Circle aCircle) {

    float testX = aCircle.x;
    float testY = aCircle.y;

    if (testX < aRect.origin.x)
        testX = aRect.origin.x;
    if (testX > (aRect.origin.x + aRect.size.width))
        testX = (aRect.origin.x + aRect.size.width);
    if (testY < aRect.origin.y)
        testY = aRect.origin.y;
    if (testY > (aRect.origin.y + aRect.size.height))
        testY = (aRect.origin.y + aRect.size.height);

    return ((aCircle.x - testX) * (aCircle.x - testX) + (aCircle.y - testY) * (aCircle.y - testY)) < aCircle.radius * aCircle.radius;
}

シェイプを操作するためのクラスを作成しました お楽しみください

public class Geomethry {
  public static boolean intersectionCircleAndRectangle(int circleX, int circleY, int circleR, int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight){
    boolean result = false;

    float rectHalfWidth = rectangleWidth/2.0f;
    float rectHalfHeight = rectangleHeight/2.0f;

    float rectCenterX = rectangleX + rectHalfWidth;
    float rectCenterY = rectangleY + rectHalfHeight;

    float deltax = Math.abs(rectCenterX - circleX);
    float deltay = Math.abs(rectCenterY - circleY);

    float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;

    do{
        // check that distance between the centerse is more than the distance between the circumcircle of rectangle and circle
        if(lengthHypotenuseSqure > ((rectHalfWidth+circleR)*(rectHalfWidth+circleR) + (rectHalfHeight+circleR)*(rectHalfHeight+circleR))){
            //System.out.println("distance between the centerse is more than the distance between the circumcircle of rectangle and circle");
            break;
        }

        // check that distance between the centerse is less than the distance between the inscribed circle
        float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
        if(lengthHypotenuseSqure < ((rectMinHalfSide+circleR)*(rectMinHalfSide+circleR))){
            //System.out.println("distance between the centerse is less than the distance between the inscribed circle");
            result=true;
            break;
        }

        // check that the squares relate to angles
        if((deltax > (rectHalfWidth+circleR)*0.9) && (deltay > (rectHalfHeight+circleR)*0.9)){
            //System.out.println("squares relate to angles");
            result=true;
        }
    }while(false);

    return result;
}

public static boolean intersectionRectangleAndRectangle(int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight, int rectangleX2, int rectangleY2, int rectangleWidth2, int rectangleHeight2){
    boolean result = false;

    float rectHalfWidth = rectangleWidth/2.0f;
    float rectHalfHeight = rectangleHeight/2.0f;
    float rectHalfWidth2 = rectangleWidth2/2.0f;
    float rectHalfHeight2 = rectangleHeight2/2.0f;

    float deltax = Math.abs((rectangleX + rectHalfWidth) - (rectangleX2 + rectHalfWidth2));
    float deltay = Math.abs((rectangleY + rectHalfHeight) - (rectangleY2 + rectHalfHeight2));

    float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;

    do{
        // check that distance between the centerse is more than the distance between the circumcircle
        if(lengthHypotenuseSqure > ((rectHalfWidth+rectHalfWidth2)*(rectHalfWidth+rectHalfWidth2) + (rectHalfHeight+rectHalfHeight2)*(rectHalfHeight+rectHalfHeight2))){
            //System.out.println("distance between the centerse is more than the distance between the circumcircle");
            break;
        }

        // check that distance between the centerse is less than the distance between the inscribed circle
        float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
        float rectMinHalfSide2 = Math.min(rectHalfWidth2, rectHalfHeight2);
        if(lengthHypotenuseSqure < ((rectMinHalfSide+rectMinHalfSide2)*(rectMinHalfSide+rectMinHalfSide2))){
            //System.out.println("distance between the centerse is less than the distance between the inscribed circle");
            result=true;
            break;
        }

        // check that the squares relate to angles
        if((deltax > (rectHalfWidth+rectHalfWidth2)*0.9) && (deltay > (rectHalfHeight+rectHalfHeight2)*0.9)){
            //System.out.println("squares relate to angles");
            result=true;
        }
    }while(false);

    return result;
  } 
}

修正されたコードは100%動作しています:

public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
{
    var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                     (rectangle.Y + rectangle.Height / 2));

    var w = rectangle.Width  / 2;
    var h = rectangle.Height / 2;

    var dx = Math.Abs(circle.X - rectangleCenter.X);
    var dy = Math.Abs(circle.Y - rectangleCenter.Y);

    if (dx > (radius + w) || dy > (radius + h)) return false;

    var circleDistance = new PointF
                             {
                                 X = Math.Abs(circle.X - rectangle.X - w),
                                 Y = Math.Abs(circle.Y - rectangle.Y - h)
                             };

    if (circleDistance.X <= (w))
    {
        return true;
    }

    if (circleDistance.Y <= (h))
    {
        return true;
    }

    var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                                    Math.Pow(circleDistance.Y - h, 2);

    return (cornerDistanceSq <= (Math.Pow(radius, 2)));
}

バッサムアルジリ

このための高速な1行のテストがあります:

if (length(max(abs(center - rect_mid) - rect_halves, 0)) <= radius ) {
  // They intersect.
}

これは、 rect_halves が長方形の中央から角を指す正のベクトルである、軸に沿った場合です。 length()内の式は、 center から長方形の最も近い点までのデルタベクトルです。これはどの次元でも機能します。

  • 最初に、長方形と円の正接が重なり合っているかどうかを確認します(簡単です)。重ならない場合、衝突しません。
  • 円の中心が長方形の内側にあるかどうかを確認します(簡単)。内部にある場合、衝突します。
  • 長方形の辺から円の中心までの最小二乗距離を計算します(少し難しい)。半径の2乗よりも低い場合は衝突し、衝突しない場合は衝突しません。

効率的です。理由は次のとおりです。

  • まず、安価なアルゴリズムを使用して最も一般的なシナリオをチェックし、衝突しないことが確実な場合は終了します。
  • 次に、安価なアルゴリズムを使用して次に最も一般的なシナリオをチェックし(平方根を計算せず、2乗値を使用します)、衝突が確認されたら終了します。
  • 次に、より高価なアルゴリズムを実行して、四角形の境界との衝突をチェックします。

必要でない場合、高価なピタゴラスを避ける方法があります-すなわち。長方形の境界ボックスと円が交差しない場合。

そして、非ユークリッドでも動作します:

class Circle {
 // create the bounding box of the circle only once
 BBox bbox;

 public boolean intersect(BBox b) {
    // test top intersect
    if (lat > b.maxLat) {
        if (lon < b.minLon)
            return normDist(b.maxLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.maxLat, b.maxLon) <= normedDist;
        return b.maxLat - bbox.minLat > 0;
    }

    // test bottom intersect
    if (lat < b.minLat) {
        if (lon < b.minLon)
            return normDist(b.minLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.minLat, b.maxLon) <= normedDist;
        return bbox.maxLat - b.minLat > 0;
    }

    // test middle intersect
    if (lon < b.minLon)
        return bbox.maxLon - b.minLon > 0;
    if (lon > b.maxLon)
        return b.maxLon - bbox.minLon > 0;
    return true;
  }
}
  • minLat、maxLatはminY、maxYで置き換えることができ、minLon、maxLonでも同じです。minX、maxXで置き換えます
  • normDistは、完全な距離の計算よりも少し速い方法です。例えば。ユークリッド空間の平方根なし(または、haversineの他の多くのものなし): dLat =(lat-circleY); dLon =(lon-circleX); normed = dLat * dLat + dLon * dLon 。もちろん、そのnormDistメソッドを使用する場合は、円に対して normedDist = dist * dist; を作成する必要があります

完全な BBox および GraphHopper プロジェクトの円コード。

SQLを使用して地理座標で円/長方形の衝突を計算する必要がある場合、
これは、 e.James推奨アルゴリズムのOracle 11での私の実装です。

入力には、円座標、km単位の円半径、および長方形の2つの頂点座標が必要です。

CREATE OR REPLACE FUNCTION "DETECT_CIRC_RECT_COLLISION"
(
    circleCenterLat     IN NUMBER,      -- circle Center Latitude
    circleCenterLon     IN NUMBER,      -- circle Center Longitude
    circleRadius        IN NUMBER,      -- circle Radius in KM
    rectSWLat           IN NUMBER,      -- rectangle South West Latitude
    rectSWLon           IN NUMBER,      -- rectangle South West Longitude
    rectNELat           IN NUMBER,      -- rectangle North Est Latitude
    rectNELon           IN NUMBER       -- rectangle North Est Longitude
)
RETURN NUMBER
AS
    -- converts km to degrees (use 69 if miles)
    kmToDegreeConst     NUMBER := 111.045;

    -- Remaining rectangle vertices 
    rectNWLat   NUMBER;
    rectNWLon   NUMBER;
    rectSELat   NUMBER;
    rectSELon   NUMBER;

    rectHeight  NUMBER;
    rectWIdth   NUMBER;

    circleDistanceLat   NUMBER;
    circleDistanceLon   NUMBER;
    cornerDistanceSQ    NUMBER;

BEGIN
    -- Initialization of remaining rectangle vertices  
    rectNWLat := rectNELat;
    rectNWLon := rectSWLon;
    rectSELat := rectSWLat;
    rectSELon := rectNELon;

    -- Rectangle sides length calculation
    rectHeight := calc_distance(rectSWLat, rectSWLon, rectNWLat, rectNWLon);
    rectWidth := calc_distance(rectSWLat, rectSWLon, rectSELat, rectSELon);

    circleDistanceLat := abs( (circleCenterLat * kmToDegreeConst) - ((rectSWLat * kmToDegreeConst) + (rectHeight/2)) );
    circleDistanceLon := abs( (circleCenterLon * kmToDegreeConst) - ((rectSWLon * kmToDegreeConst) + (rectWidth/2)) );

    IF circleDistanceLon > ((rectWidth/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat > ((rectHeight/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLon <= (rectWidth/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat <= (rectHeight/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;


    cornerDistanceSQ := POWER(circleDistanceLon - (rectWidth/2), 2) + POWER(circleDistanceLat - (rectHeight/2), 2);

    IF cornerDistanceSQ <=  POWER(circleRadius, 2) THEN
        RETURN 0;  --  -1 => NO Collision ; 0 => Collision Detected
    ELSE
        RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
END;    

機能します。1週間前にこれを理解しましたが、今ではテストを始めました。

double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
                          cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle

if((theta >  Math.PI/4 && theta <  3*Math.PI / 4) ||
   (theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
    dBox = sqr.getS() / (2*Math.sin(theta));
} else {
    dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
                    Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
                              Math.pow(sqr.getY()-cir.getY(), 2)));
def colision(rect, circle):
dx = rect.x - circle.x
dy = rect.y - circle.y
distance = (dy**2 + dx**2)**0.5
angle_to = (rect.angle + math.atan2(dx, dy)/3.1415*180.0) % 360
if((angle_to>135 and angle_to<225) or (angle_to>0 and angle_to<45) or (angle_to>315 and angle_to<360)):
    if distance <= circle.rad/2.+((rect.height/2.0)*(1.+0.5*abs(math.sin(angle_to*math.pi/180.)))):
        return True
else:
    if distance <= circle.rad/2.+((rect.width/2.0)*(1.+0.5*abs(math.cos(angle_to*math.pi/180.)))):
        return True
return False

長方形の4つのエッジがあると仮定すると、エッジから円の中心までの距離をチェックし、半径よりも小さい場合、形状は交差します。

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

長方形が円と交差する場合、長方形の1つ以上のコーナーポイントが円の内側にある必要があります。長方形の4つのポイントがA、B、C、Dであるとします。少なくとも1つは円と交差する必要があります。そのため、1点から円の中心までの距離が円の半径よりも小さい場合、円と交差する必要があります。距離を取得するには、ピタゴラスの定理を使用できます。

H^2 = A^2 + B^2

この手法にはいくつかの制限があります。しかし、ゲーム開発者にとってはうまく機能します。特に衝突検出

Arvoのアルゴリズムの良いアップデートです

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top