-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.py
63 lines (46 loc) · 1.58 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
from math import sqrt
class Vector2(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.thresh = 0.00001
def __str__(self):
return "<"+str(self.x) + ", " + str(self.y) +">"
def asTuple(self):
return self.x, self.y
def asInt(self):
return int(self.x), int(self.y)
def magnitudeSquared(self):
return self.x**2 + self.y**2
def magnitude(self):
return sqrt(self.magnitudeSquared())
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2(self.x - other.x, self.y - other.y)
def __neg__(self):
return Vector2(-self.x, -self.y)
def __mul__(self, scalar):
return Vector2(self.x * scalar, self.y * scalar)
def __div__(self, scalar):
if scalar != 0:
return Vector2(self.x / float(scalar), self.y / float(scalar))
return None
def __truediv__(self, scalar):
return self.__div__(scalar)
def __eq__(self, other):
if abs(self.x - other.x) < self.thresh:
if abs(self.y - other.y) < self.thresh:
return True
return False
def __hash__(self):
return id(self)
def copy(self):
return Vector2(self.x, self.y)
def dot(self, other):
return self.x*other.x + self.y*other.y
def normalize(self):
mag = self.magnitude()
if mag != 0:
return self.__div__(mag)
return None