-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.py
More file actions
81 lines (63 loc) · 2.04 KB
/
vector.py
File metadata and controls
81 lines (63 loc) · 2.04 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
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
"""
Vector maths
"""
# Copyright (C) 2008 James Fargher
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
import math
(VEC_X, VEC_Y, VEC_Z) = range(3)
class Vec2(object):
"""2-dimensional vector"""
def __init__(self, x=0.0, y=0.0):
self.__x = x
self.__y = y
@classmethod
def from_angle(cls, angle, magnitude=1.0):
x = math.cos(angle) * magnitude
y = math.sin(angle) * magnitude
return cls(x, y)
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
def magnitude(self):
"""Return the length or magnitude"""
return math.sqrt(self.x ** 2 + self.y ** 2)
def normalised(self):
"""Return a normalised copy"""
mag = self.magnitude()
if mag == 0.0:
return Vec2(self.x, self.y)
return Vec2(self.x / mag, self.y / mag)
def scale(self, scalar):
"""Return a scaled copy"""
new_x = self.x * scalar
new_y = self.y * scalar
return Vec2(new_x, new_y)
def dot(self, other):
"""Vector multiplication as scalar
Dot product of self by other"""
return self[VEC_X] * other[VEC_X] + self[VEC_Y] * other[VEC_Y]
def __add__(self, other):
new_x = self.x + other[VEC_X]
new_y = self.y + other[VEC_Y]
return Vec2(new_x, new_y)
__iadd__ = __add__
def __sub__(self, other):
new_x = self.x - other[VEC_X]
new_y = self.y - other[VEC_Y]
return Vec2(new_x, new_y)
__isub__ = __sub__
def __getitem__(self, name):
if name == VEC_X:
return self.x
elif name == VEC_Y:
return self.y
raise IndexError('Vec2 index out of range')
def __len__(self):
return 2