Mercurial > traipse_dev
comparison orpg/mapper/map_utils.py @ 0:4385a7d0efd1 grumpy-goblin
Deleted and repushed it with the 'grumpy-goblin' branch. I forgot a y
author | sirebral |
---|---|
date | Tue, 14 Jul 2009 16:41:58 -0500 |
parents | |
children | 072ffc1d466f |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4385a7d0efd1 |
---|---|
1 #------------------------------------------------ | |
2 # file: map_utils.py | |
3 # | |
4 # This file contains generic utility functions | |
5 # for use in the openrpg mapping system | |
6 # ----------------------------------------------- | |
7 | |
8 import math | |
9 | |
10 #----------------------------------------------------------------------- | |
11 # distance_between() | |
12 # Returns the distance between two points | |
13 #----------------------------------------------------------------------- | |
14 def distance_between( x1, y1, x2, y2 ): | |
15 "Returns the distance between two points" | |
16 dx = x2 - x1 | |
17 dy = y2 - y1 | |
18 return math.sqrt( dx*dx + dy*dy ) | |
19 | |
20 #----------------------------------------------------------------------- | |
21 # proximity_test() | |
22 # Tests if 'test_point' (T) is close (within 'threshold' units) to the | |
23 # line segment 'start_point' to 'end_point' (PQ). | |
24 # | |
25 # The closest point (R) to T on the line PQ is given by: | |
26 # R = P + u (Q - P) | |
27 # TR is perpendicular to PQ so: | |
28 # (T - R) dot (Q - P) = 0 | |
29 # Solving these two equations gives the equation for u (see below). | |
30 # | |
31 # If u < 0 or u > 1 then R is not within the line segment and we simply | |
32 # test against point P or Q. | |
33 #----------------------------------------------------------------------- | |
34 def proximity_test( start_point, end_point, test_point, threshold ): | |
35 "Test if a point is close to a line segment" | |
36 x1,y1 = start_point | |
37 x2,y2 = end_point | |
38 xt,yt = test_point | |
39 x1 = float(x1) | |
40 x2 = float(x2) | |
41 y1 = float(y1) | |
42 y2 = float(y2) | |
43 xt = float(xt) | |
44 yt = float(yt) | |
45 | |
46 # Coincident points? | |
47 if x1 == x2 and y1 == y2: | |
48 d = distance_between(xt, yt, x1, y1) | |
49 else: | |
50 dx = x2 - x1 | |
51 dy = y2 - y1 | |
52 u = ((xt - x1) * dx + (yt - y1) * dy) / (dx*dx + dy*dy) | |
53 if u < 0: | |
54 d = distance_between(xt, yt, x1, y1) | |
55 elif u > 1: | |
56 d = distance_between(xt, yt, x2, y2) | |
57 else: | |
58 xr = x1 + u * dx | |
59 yr = y1 + u * dy | |
60 d = distance_between(xt, yt, xr, yr) | |
61 return d <= threshold |