There are two steps to detect the collision of sphere and rectangle:

1. Find the point within rectangle which is the nearest point to sphere

2. Check the nearest point is in sphere or not. If it is in sphere, they collide each other.

To find the nearest point:

a. Calculate the vector from the sphere center to renctangle center(In figure, it is D vector.)

Sphere-Rect 

b. Project the D vector to W & H vector, and calculate the scale of each vector

c. Clamp the scale to -1 ~ 1

d. Multiply W & H by each scale, then add to center of rectangle. And we get the nearest point

 

Here is the pseudo code:

bool CollisionSphereRect(Sphere& s, Rect& rect)
{
    vec3 d;
    vec3 nearest;
    float s1, s2;
    d = s.center - rect.center;
    s1 = Dot(d, rect.w);
    s1 /= Dot(rect.w, rect.w);
    s1 = Clamp(s1, -1, 1);
    s2 = Dot(d, rect.h);
    s2 /= Dot(rect.h, rect.h);
    s2 = Clamp(s2, -1, 1);
    nearest = rect.center + s1*rect.w + s2*rect.h;

    return CollisionSpherePoint(s, nearest);
}

創作者介紹
創作者 Duke Rabbit's Game Zone 的頭像
lijy

Duke Rabbit's Game Zone

lijy 發表在 痞客邦 留言(0) 人氣( 50 )