I've seen many tutorials for simple rectangle or circle-based collision detection with pygame.

But how can I do more complex collisions with arbitrary polygons?

Is the only option pixel-based collision detection?


3 Answers 3


Short answer: yep. :P

Long answer: rectangle collisions are built into Pygame. Circle collisions are simple math. Use Box2D for anything more complicated.

  • \$\begingroup\$ Thanks for the reply! I thought Box2d was just for physics. It's good for collision detection too? I don't want "realistic" physics, just detecting collisions. \$\endgroup\$
    – Sara
    Jun 27, 2012 at 2:28
  • 3
    \$\begingroup\$ Collision detection and collision response are fundamental for physics libraries. \$\endgroup\$
    – House
    Jun 27, 2012 at 3:27

Have a look at pylygon.

a polygon object with rotation and collision detection methods.

It's rather lightweight compared to a full blown physics library, and collision detection is as simple as:

r = obj1.C - target_pos
results = obj1.raycast(obj2, r, self_theta = obj1_rotation)
if results:
    # collision
    obj1.move_ip(*-r) # move the object

I have developed a function for the collision of a circle and a rotated rectangle. Not very complex but this is everything I need for collision:

#requieres math imported, width, height of rect,
#angle between rect and point to collide with, rotation angle of rect
def rect_distance(b_side_x,b_side_y,angle_b_p,b_angle=0):
   w1 = angle_b_p - b_angle
   w1 %= 360
   w_b = round(math.atan(b_side_x/b_side_y)/math.pi*180)
   if (w1 > 90 - w_b and w1 < 90 + w_b) or (w1 > 270 - w_b and w1 < 270 + w_b):
      distance = round(b_side_y/2/math.sin(w1*math.pi/180))
      distance = round(b_side_x/2/math.cos(w1*math.pi/180))
   return abs(distance)
#returns distance between middle and side of a (rotated) rect under an angle

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .