Answers for "Box and Circle collisions C++"

C++
0

Box and Circle collisions C++

bool AABBvsCircle( Manifold *m )
{
  // Setup a couple pointers to each object
  Object *A = m->A
  Object *B = m->B
 
  // Vector from A to B
  Vec2 n = B->pos - A->pos
 
  // Closest point on A to center of B
  Vec2 closest = n
 
  // Calculate half extents along each axis
  float x_extent = (A->aabb.max.x - A->aabb.min.x) / 2
  float y_extent = (A->aabb.max.y - A->aabb.min.y) / 2
 
  // Clamp point to edges of the AABB
  closest.x = Clamp( -x_extent, x_extent, closest.x )
  closest.y = Clamp( -y_extent, y_extent, closest.y )
 
  bool inside = false
 
  // Circle is inside the AABB, so we need to clamp the circle's center
  // to the closest edge
  if(n == closest)
  {
    inside = true
 
    // Find closest axis
    if(abs( n.x ) > abs( n.y ))
    {
      // Clamp to closest extent
      if(closest.x > 0)
        closest.x = x_extent
      else
        closest.x = -x_extent
    }
 
    // y axis is shorter
    else
    {
      // Clamp to closest extent
      if(closest.y > 0)
        closest.y = y_extent
      else
        closest.y = -y_extent
    }
  }
 
  Vec2 normal = n - closest
  real d = normal.LengthSquared( )
  real r = B->radius
 
  // Early out of the radius is shorter than distance to closest point and
  // Circle not inside the AABB
  if(d > r * r && !inside)
    return false
 
  // Avoided sqrt until we needed
  d = sqrt( d )
 
  // Collision normal needs to be flipped to point outside if circle was
  // inside the AABB
  if(inside)
  {
    m->normal = -n
    m->penetration = r - d
  }
  else
  {
    m->normal = n
    m->penetration = r - d
  }
 
  return true
}
Posted by: Guest on June-19-2021

Browse Popular Code Answers by Language