Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

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.

share|improve this answer
    
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. –  Sara Jun 27 '12 at 2:28
3  
Collision detection and collision response are fundamental for physics libraries. –  Byte56 Jun 27 '12 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
else:
    obj1.move_ip(*-r) # move the object
share|improve this answer

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))
   else:
      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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.