내가 원이 사각형에 충돌 한 경우 검출하는 알고리즘을 필요 exampe 완료하고,이 게시물보고 : 나는 ShreevatsaR의 대답 가야처럼 Circle-Rectangle collision detection (intersection)원 - 사각형 충돌 감지는
것 같습니다,하지만 난 오전 수학 바보, 그리고 어떻게 알고리즘을 완료 해야할지 모르겠다. 아무도 나를 위해 완벽한 예제를 만들 시간을 찾을 수 없습니까, 나는 이것에 대한 그물을 검색하고, 아직 작동 예제를 발견하지 못했습니다.
당신에게제작 : Soeren 대단히 감사합니다
편집 :
여기 좋아 내 시도이다. 작동하지 않고 충돌을 감지하지 못합니다.
typedef struct {
double x;
double y;
} point;
typedef struct {
point one;
point two;
} segment;
typedef struct {
point center;
double radius;
} circle;
typedef struct {
point p;
int width;
int height;
point a;
point b;
point c;
point d;
} rectangle;
double slope(point one, point two) {
return (double)(one.y-two.y)/(one.x-two.x);
}
double distance(point p, segment s) {
// Line one is the original line that was specified, and line two is
// the line we're constructing that runs through the specified point,
// at a right angle to line one.
//
// if it's a vertical line return the horizontal distance
if (s.one.x == s.two.x)
return fabs(s.one.x - p.x);
// if it's a horizontal line return the vertical distance
if (s.one.y == s.two.y)
return fabs(s.one.y - p.y);
// otherwise, find the slope of the line
double m_one = slope(s.one, s.two);
// the other slope is at a right angle.
double m_two = -1.0/m_one;
// find the y-intercepts.
double b_one = s.one.y - s.one.x * m_one;
double b_two = p.y - p.x * m_two;
// find the point of intersection
double x = (b_two - b_one)/(m_one - m_two);
double y = m_one * x + b_one;
// find the x and y distances
double x_dist = x - p.x;
double y_dist = y - p.y;
// and return the total distance.
return sqrt(x_dist * x_dist + y_dist * y_dist);
}
bool intersectsCircle(segment s, circle c) {
return distance(c.center, s) <= c.radius;
}
bool pointInRectangle(point p, rectangle r)
{
float right = r.p.x + r.width;
float left = r.p.x - r.width;
float top = r.p.y + r.height;
float bottom = r.p.y - r.height;
return ((left <= p.x && p.x <= right) && (top <= p.y && p.y <= bottom));
}
bool intersect(circle c, rectangle r) {
segment ab;
ab.one = r.a;
ab.two = r.b;
segment bc;
ab.one = r.b;
ab.two = r.c;
segment cd;
ab.one = r.c;
ab.two = r.d;
segment da;
ab.one = r.d;
ab.two = r.a;
return pointInRectangle(c.center, r) ||
intersectsCircle(ab, c) ||
intersectsCircle(bc, c) ||
intersectsCircle(cd, c) ||
intersectsCircle(da, c);
}
연결된 질문에 원/사각형 충돌 감지 기능이 완벽하게 구현되었습니다. 저쪽에, 나는 당신이 진지한 노력을하고 당신의 시도를 보여주지 않는 한, 누군가가 기꺼이 도울 것이라는 것을 의심한다. – patros