Circle-Rectangle collision detection (intersection)

前端 未结 24 1292
无人共我
无人共我 2020-11-22 02:55

How can I tell whether a circle and a rectangle intersect in 2D Euclidean space? (i.e. classic 2D geometry)

24条回答
  •  有刺的猬
    2020-11-22 02:58

    Works, just figured this out a week ago, and just now got to testing it.

    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)));
    

提交回复
热议问题