-
Notifications
You must be signed in to change notification settings - Fork 2
/
vector.lua
89 lines (72 loc) · 1.61 KB
/
vector.lua
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
-- A custom vector class
Vector = {
identity = "Vector class",
}
function Vector:new(x, y)
local instance = {}
setmetatable(instance, self)
self.__index = self
instance.x = x
instance.y = y
return instance
end
function Vector:toString()
return "(" .. self.x .. ", " .. self.y .. ")"
end
function Vector:isNearby(threshold, a)
if a == self then
return false
end
return self:distance(a) < threshold
end
function Vector:distance(a)
return math.sqrt((self.x - a.x)^2 + (self.y - a.y)^2)
end
function Vector:__add(a)
return Vector:new(self.x + a.x, self.y + a.y)
end
function Vector:__sub(a)
return Vector:new(self.x - a.x, self.y - a.y)
end
function Vector:__mul(num)
return Vector:new(self.x * num, self.y * num)
end
function Vector:__div(num)
if (num ~= 0) then
return Vector:new(self.x / num, self.y / num)
else
return self
end
end
function Vector:__unm()
return Vector:new(-self.x, -self.y)
end
function Vector:dot(a)
return self.x * a.x + self.y * a.y
end
function Vector:r()
return math.sqrt(self:dot(self))
end
function Vector:norm()
return Vector:new(self.x, self.y) / self:r()
end
function Vector:ang()
return math.atan(self.y / self.x)
end
-- a = Vector:new(2,2)
-- print(a:toString())
-- print(math.deg(a:ang()))
-- b = Vector:new(5,6)
-- print(a:to_s())
-- print(b:to_s())
-- print(a:distance(b))
-- print(a:is_nearby(10, a))
-- print(a:is_nearby(10, b))
-- print(a:is_nearby(3, b))
-- print((a+b):to_s())
-- print((b-a):to_s())
-- print((a*3):to_s())
-- print((a/3):to_s())
-- print((-a):to_s())
-- print(a:dot(b))
-- print(a:r())