-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.lua
126 lines (93 loc) · 2.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
if math.infinity == nil then
math.infinity = "INF"
end
-- @param _construct: map args --> object
-- @param tcurtsnoc_: map object --> args
Klass = function (_construct, tcurtsnoc_)
local constructor
local function copy(o)
return constructor(tcurtsnoc_(o))
end
constructor = function (...)
local instance = _construct(unpack({...}))
instance.copy = function ()
return copy(instance)
end
return instance
end
return constructor
end
-- a point!
Point = Klass((function ()
local constructor = function (x, y)
local x, y = x, y
local instance = {
getX = function ()
return x
end,
getY = function ()
return y
end,
setX = function (n)
x = n
end,
setY = function (n)
y = n
end,
}
return instance
end
local copy = function (o)
return o.getX(), o.getY()
end
return constructor, copy
end)())
-- a vector is a glorified point!
Vector = Klass((function ()
local constructor
_constructor = function (x, y)
local p = Point(x, y)
-- this is the "magnitude" of the vector, or its length as a line
p.length = function ()
return math.sqrt(p.getX() ^ 2 + p.getY() ^ 2)
end
p.getSlope = function ()
local slope
-- the slope is infinite
if -0.1 < x and x < 0.1 then
slope = math.infinity
else
slope = y / x
end
return slope
end
-- returns a new vector with a length of 1, for stuff
p.to_unit = function ()
local mag = p.length()
if mag == 0 then return Vector(0, 0) end
return Vector(p.getX() / mag, p.getY() / mag)
end
-- some operators like dot and plus. Write more as you need them
p.dot = function (o)
local x = p.getX() * o.getX()
local y = p.getY() * o.getY()
return constructor(x, y)
end
p.plus = function (o)
local x = p.getX() + o.getX()
local y = p.getY() + o.getY()
return constructor(x, y)
end
p.times = function (s)
local x = s*p.getX()
local y = s*p.getY()
return constructor(x, y)
end
return p
end
constructor = _constructor
local copy = function (o)
return o.getX(), o.getY()
end
return constructor, copy
end)())