PageRenderTime 223ms CodeModel.GetById 81ms app.highlight 6ms RepoModel.GetById 135ms app.codeStats 0ms

/demos/bin/space-aliens/runtime/paths.py

http://game-baker.googlecode.com/
Python | 65 lines | 43 code | 15 blank | 7 comment | 6 complexity | 559c963934fad40a7889fcb96f989f1e MD5 | raw file
 1from math import sqrt as sqrt
 2from gb_exceptions import *
 3
 4class bezier_curve(object):
 5    def __init__(self):
 6        self.points=[]
 7        self.total_length = 0
 8        pass
 9
10    def length(self):
11        """Returns actual (unparametrisized) length of curve"""
12        return self.total_length
13
14    def add_point(self,x,y):
15        """Adds a point"""
16        self.points.append((x,y))
17
18    def get_position(self,t):
19        """Gets unparametrisized position from parameter t"""
20        pass
21
22
23class linear_bezier(bezier_curve):
24    """Simple Linear Bezier Curves - i.e. lines between points"""
25
26    def add_point(self,x,y):
27        self.points.append((x,y))
28        self.total_length = 0
29        for i in range(len(self.points)-1):
30            self.total_length += sqrt(
31                    (self.points[i][0] - self.points[i+1][0])**2 + 
32                    (self.points[i][1] - self.points[i+1][1])**2
33                    )
34
35    def get_position(self,t=0.):
36        if float(t)> 1.:
37            t = 1.
38        
39        # find which segment we're on
40        i = 0
41        length = 0.
42        t_times_total = t*self.total_length
43        while i < len(self.points):
44            segment_length = sqrt(
45                    (self.points[i][0] - self.points[i+1][0])**2 + 
46                    (self.points[i][1] - self.points[i+1][1])**2
47                    )
48            if length + segment_length > t_times_total or (i+2 == len(self.points)):
49                break
50            else: 
51                length += segment_length
52            i+=1
53
54
55        # should be at the segment starting with point i
56        # find out how far along this segment we are
57        dist = ( t_times_total - length ) / (segment_length)
58
59        vector = (self.points[i+1][0] - self.points[i][0],
60                    self.points[i+1][1] - self.points[i][1])
61        
62        return (self.points[i][0] + dist * vector[0],
63                self.points[i][1] + dist * vector[1])
64            
65