forked from rougier/from-python-to-numpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvec2.py
More file actions
46 lines (35 loc) · 1.32 KB
/
vec2.py
File metadata and controls
46 lines (35 loc) · 1.32 KB
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
import math
from collections import namedtuple
def struct(name, members):
cls = namedtuple(name, members)
cls.__repr__ = lambda self: "%s(%s)" % (name, ','.join(str(s) for s in self))
return cls
class vec2(struct('vec2', ('x', 'y'))):
def __add__(self, other):
if isinstance(other, vec2):
return vec2(self.x+other.x, self.y+other.y)
return vec2(self.x+other, self.y+other)
def __sub__(self, other):
if isinstance(other, vec2):
return vec2(self.x-other.x, self.y-other.y)
return vec2(self.x-other, self.y-other)
def __mul__(self, other):
if isinstance(other, vec2):
return vec2(self.x*other.x, self.y*other.y)
return vec2(self.x*other, self.y*other)
def __truediv__(self, other):
if isinstance(other, vec2):
return vec2(self.x/other.x, self.y/other.y)
return vec2(self.x/other, self.y/other)
def length(self):
return math.hypot(self.x, self.y)
def normalized(self):
length = self.length()
if not length:
length = 1.0
return vec2(self.x/length, self.y/length)
def limited(self, maxlength=1.0):
length = self.length()
if length > maxlength:
return vec2(maxlength*self.x/length, maxlength*self.y/length)
return self