]> Untitled Git - lightcycles-love.git/blob - player.lua
Fixed crashes
[lightcycles-love.git] / player.lua
1 require 'vec2'
2
3 Player = {}
4 Player.name = 'none'
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:__tostring()
34     return self.name
35 end
36
37 function Player:drawPath()
38     if #self.path >= 4 then
39         love.graphics.setLineWidth(2)
40         love.graphics.setColor(self.color)
41         love.graphics.line(self.path)
42     end
43 end
44
45 function Player:draw()
46     love.graphics.setColor(self.color)
47     love.graphics.rectangle(
48         'fill',
49         self.position.x-self.width/2,
50         self.position.y-self.height/2,
51         self.width,
52         self.height
53         )
54
55     -- add current position
56     self:recordPosition()
57     self:drawPath()
58     table.remove(self.path)
59     table.remove(self.path)
60 end
61
62 function Player:recordPosition()
63     table.insert(self.path, self.position.x)
64     table.insert(self.path, self.position.y)
65 end
66
67 function Player:multiple_keys_are_pressed()
68     local count = 0
69     for key,_ in pairs(self.keys) do
70         if love.keyboard.isDown(key) then
71             count = count + 1
72         end
73     end
74     return count > 1
75 end
76
77 function Player:update(dt)
78     if not self:multiple_keys_are_pressed() then
79         for key, name in pairs(self.keys) do
80             if love.keyboard.isDown(key)
81             and self.vector ~= self.vectors[name]
82             and (self.vector + self.vectors[name]):length() > 0
83             then
84                 self.vector = self.vectors[name]
85                 self:recordPosition()
86                 break
87             end
88         end
89     end
90     self.position = self.position + self.vector * self.acceleration * dt
91 end