-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvector.py
88 lines (67 loc) · 2.1 KB
/
vector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import math
class Vec2d(object):
__slots__ = ['x', 'y']
def __init__(self, x=0.0, y=0.0):
self.x = float(x)
self.y = float(y)
def __add__(self, other):
return Vec2d(self.x+other.x, self.y+other.y)
def __sub__(self, other):
return Vec2d(self.x-other.x, self.y-other.y)
def __mul__(self, scalar):
return Vec2d(self.x*scalar, self.y*scalar)
def __div__(self, scalar):
return Vec2d(self.x/scalar, self.y/scalar)
def __rmul__(self, scalar):
return Vec2d(self.x*scalar, self.y*scalar)
def __rdiv__(self, scalar):
return Vec2d(self.x/scalar, self.y/scalar)
@property
def magnitude(self):
if self.y == 0:
return abs(self.x)
elif self.x == 0:
return abs(self.y)
else:
return math.hypot(self.x, self.y)
@property
def magnitude_sq(self):
return self.x ** 2 + self.y ** 2
@property
def angle(self):
return math.degrees(math.atan2(self.x, self.y))
@property
def slope(self):
if self.x == 0:
return 0
return self.y/self.x
def zero(self):
self.x = 0
self.y = 0
def normalize(self):
l = self.magnitude
if l == 0: return self
self.x /= l
self.y /= l
@property
def normal(self):
l = self.magnitude
if l == 0: return Vec2d()
return Vec2d(self.x / l, self.y / l)
def rotate(self, angle):
angle = math.radians(angle)
l = self.magnitude
self.x = math.sin(angle) * l
self.y = math.cos(angle) * l
def rotated(self, angle):
angle = math.radians(angle)
sin_a = math.sin(angle)
cos_a = math.cos(angle)
s = Vec2d()
s.x = (self.x * cos_a) - (self.y * sin_a)
s.y = (self.y * cos_a) + (self.x * sin_a)
return s
def copy(self):
return Vec2d(self.x, self.y)
def __repr__(self):
return 'Vec2d(%.2f, %.2f)' % (self.x, self.y)