Don't get me wrong .. HUMP.vector is a fine lib. This is just a quick-and-dirty snippet which may be useful for simple stuff, with an example showing a circle following the mouse at a constant speed.
Warning : for simplicity, operators rely on vector being declared globally, as in the code below.
Function naming convention goes :
- r is radians
- d is degrees
- v is vector
-to- is a conversion from prefix (or vector if none) to suffix
Code: Select all
vector = {
load = function(this, x, y) return setmetatable((not x and {x = 0, y = 0}) or (y and {x = x, y = y}) or {x = x.x or x[1] or 0, y = x.y or x[2] or 0}, vectormt) end,
normal = function(v) l = v:len(); return vector(v.x / l, v.y / l) end,
len = function(v) return math.sqrt((v.x * v.x) + (v.y * v.y)) end,
tor = function(v) return math.atan2(v.y, v.x) end,
tod = function(v) return math.atan2(v.y, v.x) * (180 / math.pi) end,
rtov = function(r) return vector(math.cos(r), math.sin(r)) end,
dtov = function(d) return vector.rtovec(d * (math.pi / 180)) end,
}
setmetatable(vector, {__call = vector.load})
vectormt = {
__index = vector,
__add = function(this, v) return (type(v) == 'table' and vector(this.x + v.x, this.y + v.y)) or vector(this.x + v, this.y + v) end,
__sub = function(this, v) return (type(v) == 'table' and vector(this.x - v.x, this.y - v.y)) or vector(this.x - v, this.y - v) end,
__mul = function(this, v) return (type(v) == 'table' and vector(this.x * v.x, this.y * v.y)) or vector(this.x * v, this.y * v) end,
__div = function(this, v) return (type(v) == 'table' and vector(this.x / v.x, this.y / v.y)) or vector(this.x / v, this.y / v) end,
__pow = function(this, v) return (type(v) == 'table' and vector(this.x ^ v.x, this.y ^ v.y)) or vector(this.x ^ v, this.y ^ v) end,
__unm = function(this) return vector(0 - this.x, 0 - this.y) end,
__tostring = function(this) return 'vector(x = '..this.x..', y = '..this.y..')' end,
}
mouse = function() return vector(love.mouse.getX(), love.mouse.getY()) end
love.load = function() player = {p = vector(64, 64), speed = 128} end
love.update = function(dt) player.p = player.p + ((mouse() - player.p):normal() * (player.speed * dt)) end
love.draw = function() love.graphics.circle('fill', player.p.x, player.p.y, 8, 8) end
Comments? Suggestions? Etc?