1683e58f6ca70fa583e65e9e967835d2c6831472
1 """Simple collision check.
3 This module provides simple collision checking appropriate for
4 shmups. It provides a routine to check whether two moving circles
5 collided during the past frame.
7 An equivalent C-based version will be used automatically if it was
8 compiled and installed with the module. If available, it will be noted
9 in the docstrings for the functions.
13 from bulletml.collision import collides
15 for bullet in bullets:
16 if collides(player, bullet): ... # Kill the player.
19 from __future__
import division
22 """Return true if two circles are overlapping.
24 Usually, you'll want to use the 'collides' method instead, but
25 this one can be useful for just checking to see if the player has
26 entered an area or hit a stationary oject.
28 (This function is unoptimized.)
33 radius
= getattr(a
, 'radius', 0.5) + getattr(b
, 'radius', 0.5)
35 return dx
* dx
+ dy
* dy
<= radius
* radius
38 """Return true if the two moving circles collide.
40 a and b should have the following attributes:
42 x, y - required, current position
43 px, py - not required, defaults to x, y, previous frame position
44 radius - not required, defaults to 0.5
46 (This function is unoptimized.)
55 # Treat b as a point, we only need one radius.
56 radius
= getattr(a
, 'radius', 0.5) + getattr(b
, 'radius', 0.5)
58 # Previous frame locations.
59 pxa
= getattr(a
, 'px', xa
)
60 pya
= getattr(a
, 'py', ya
)
61 pxb
= getattr(b
, 'px', xb
)
62 pyb
= getattr(b
, 'py', yb
)
64 # Translate b's final position to be relative to a's start.
65 # And now, circle/line collision.
66 dir_x
= pxa
+ (xb
- xa
) - pxb
67 dir_y
= pya
+ (yb
- ya
) - pyb
69 if abs(dir_x
) < 0.0001 and abs(dir_y
) < 0.0001:
70 # b did not move relative to a, so do point/circle.
73 return dx
* dx
+ dy
* dy
< radius
* radius
78 # dot(diff, dir) / dot(dir, dir)
79 t
= (diff_x
* dir_x
+ diff_y
* dir_y
) / (dir_x
* dir_x
+ dir_y
* dir_y
)
85 dist_x
= pxa
- (pxb
+ dir_x
* t
)
86 dist_y
= pya
- (pyb
+ dir_y
* t
)
89 return dist_x
* dist_x
+ dist_y
* dist_y
<= radius
* radius
91 def collides_all(a
, others
):
92 """Filter the second argument to those that collide with the first.
94 This is equivalent to filter(lambda o: collides(a, o), others),
95 but is much faster when the compiled extension is available (which
99 return filter(lambda o
: collides(a
, o
), others
)
102 from bulletml
._collision
import collides
, overlaps
, collides_all