source: skaapsteker/utils.py

Last change on this file was 627:35919d12b792, checked in by Jeremy Thurgood <firxen@…>, 12 years ago

Path-based collision minimisation and axis-projection backout.

File size: 1.2 KB
Line 
1import operator
2import functools
3
4
5def mktuple(thing):
6 if isinstance(thing, (list, tuple)):
7 return tuple(thing)
8 return (thing, thing)
9
10
11def coord_op(fun, coord, operand):
12 operand = mktuple(operand)
13 return (fun(coord[0], operand[0]),
14 fun(coord[1], operand[1]))
15
16
17def mk_cop(op):
18 return functools.partial(coord_op, op)
19
20
21def mk_cuop(op):
22 return lambda coord: (op(coord[0]), op(coord[1]))
23
24
25cadd = mk_cop(operator.add)
26csub = mk_cop(operator.sub)
27cmul = mk_cop(operator.mul)
28cdiv = mk_cop(operator.div)
29cclamp = mk_cop(lambda a, b: max(min(a, b), -b))
30cabsmax = mk_cop(lambda a, b: a if abs(a) > abs(b) else b)
31
32cint = mk_cuop(int)
33cneg = mk_cuop(lambda a: -a)
34cabs = mk_cuop(abs)
35
36
37def rect_projection(rect1, rect2):
38 if not rect1.colliderect(rect2):
39 # No collision?
40 return (0, 0)
41
42 if rect1.center[0] < rect2.center[0]:
43 x_projection = rect2.left - rect1.right
44 else:
45 x_projection = rect2.right - rect1.left
46
47 if rect1.center[1] < rect2.center[1]:
48 y_projection = rect2.top - rect1.bottom
49 else:
50 y_projection = rect2.bottom - rect1.top
51
52 if abs(x_projection) < abs(y_projection):
53 return (x_projection, 0)
54 return (0, y_projection)
55
Note: See TracBrowser for help on using the repository browser.