1 """Optimized collision detection functions."""
4 """Return true if two circles are overlapping.
6 Usually, you'll want to use the 'collides' method instead, but
7 this one can be useful for just checking to see if the player has
8 entered an area or hit a stationary oject.
10 (This function is optimized.)
33 except AttributeError:
37 except AttributeError:
40 return dx * dx + dy * dy <= radius * radius
43 cdef int _collides(float xa, float xb, float ya, float yb,
44 float pxa, float pxb, float pya, float pyb,
45 float radius_a, float radius_b):
47 """Check collision for two moving circles."""
63 radius = radius_a + radius_b
65 # Translate b's final position to be relative to a's start.
66 # And now, circle/line collision.
67 dir_x = pxa + (xb - xa) - pxb
68 dir_y = pya + (yb - ya) - pyb
70 if (dir_x < 0.0001 and dir_x > -0.0001
71 and dir_y < 0.0001 and dir_y > -0.0001):
72 # b did not move relative to a, so do point/circle.
75 return dx * dx + dy * dy < radius * radius
80 # dot(diff, dir) / dot(dir, dir)
81 t = (diff_x * dir_x + diff_y * dir_y) / (dir_x * dir_x + dir_y * dir_y)
87 dist_x = pxa - (pxb + dir_x * t)
88 dist_y = pya - (pyb + dir_y * t)
91 return dist_x * dist_x + dist_y * dist_y <= radius * radius
94 """Return true if the two moving circles collide.
96 a and b should have the following attributes:
98 x, y - required, current position
99 px, py - not required, defaults to x, y, previous frame position
100 radius - not required, defaults to 0.5
102 (This function is optimized.)
123 radius_a = getattr3(a, 'radius', 0.5)
124 radius_b = getattr3(b, 'radius', 0.5)
126 pxa = getattr3(a, 'px', xa)
127 pya = getattr3(a, 'py', ya)
128 pxb = getattr3(b, 'px', xb)
129 pyb = getattr3(b, 'py', yb)
131 return _collides(xa, xb, ya, yb, pxa, pxb, pya, pyb, radius_a, radius_b)
133 def collides_all(a, others):
134 """Filter the second argument to those that collide with the first.
136 This is equivalent to filter(lambda o: collides(a, o), others),
137 but is much faster when the compiled extension is available (which
165 radius_a = getattr3(a, 'radius', 0.5)
166 pxa = getattr3(a, 'px', xa)
167 pya = getattr3(a, 'py', ya)
176 radius_b = getattr3(b, 'radius', 0.5)
177 pxb = getattr3(b, 'px', xb)
178 pyb = getattr3(b, 'py', yb)
180 if _collides(xa, xb, ya, yb, pxa, pxb, pya, pyb, radius_a, radius_b):