]> Untitled Git - lightcycles-love.git/blob - player.lua
0e707f82858272a614287e75f29db65000bf852f
[lightcycles-love.git] / player.lua
1 require 'vec2'
2
3 Player = {}
4 Player.name = 'player'
5 Player.color = {255, 0, 0}
6 Player.width = 5
7 Player.height = 5
8 Player.acceleration = 100
9 Player.position = vec2:new(0, 0)
10 Player.vector = vec2:new(0, 0)
11 Player.path = {}
12 Player.vectors = {
13     up    = vec2:new(0, -1),
14     down  = vec2:new(0, 1),
15     left  = vec2:new(-1, 0),
16     right = vec2:new(1, 0),
17     }
18 Player.keys = {
19     w = 'up',
20     s = 'down',
21     a = 'left',
22     d = 'right',
23     }
24
25 function Player:new(o)
26     o = o or {}
27     setmetatable(o, self)
28     self.__index = self
29     o:recordPosition()
30     return o
31 end
32
33 function Player:drawPath()
34     if #self.path >= 4 then
35         love.graphics.setLineWidth(2)
36         love.graphics.setColor(self.color)
37         love.graphics.line(self.path)
38     end
39 end
40
41 function Player:draw()
42     love.graphics.setColor(self.color)
43     love.graphics.rectangle('fill', self.position.x, self.position.y, self.width, self.height)
44
45     -- add current position
46     self:recordPosition()
47     self:drawPath()
48     table.remove(self.path)
49     table.remove(self.path)
50 end
51
52 function Player:recordPosition()
53     table.insert(self.path, self.position.x + self.width/2)
54     table.insert(self.path, self.position.y + self.height/2)
55 end
56
57 function Player:update(dt)
58     for key, name in pairs(self.keys) do
59         if love.keyboard.isDown(key)
60         and self.vector ~= self.vectors[name]
61         and (self.vector + self.vectors[name]):length() > 0
62         then
63             self.vector = self.vectors[name]
64             self:recordPosition()
65             break
66         end
67     end
68     self.position = self.position + self.vector * self.acceleration * dt
69 end