]> Untitled Git - lightcycles-love.git/blob - player.lua
Fixed crashes better. Bug on collision on 1st line. Cannot tell who crashed.
[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.path.vector = Player.position
13 Player.vectors = {
14     up    = vec2:new(0, -1),
15     down  = vec2:new(0, 1),
16     left  = vec2:new(-1, 0),
17     right = vec2:new(1, 0),
18     }
19 Player.keys = {
20     w = 'up',
21     s = 'down',
22     a = 'left',
23     d = 'right',
24     }
25
26 function Player:new(o)
27     o = o or {}
28     setmetatable(o, self)
29     self.__index = self
30     o.path.vector = o.position
31     o:recordPosition()
32     return o
33 end
34
35 function Player:__tostring()
36     return self.name
37 end
38
39 function Player:drawPath()
40     local points = {}
41     local node = self.path
42     while node do
43         table.insert(points, node.vector.x)
44         table.insert(points, node.vector.y)
45         node = node.prev
46     end
47     if #points >= 4 then
48         love.graphics.setLineWidth(2)
49         love.graphics.setColor(self.color)
50         love.graphics.line(points)
51     end
52 end
53
54 function Player:draw()
55     love.graphics.setColor(self.color)
56     love.graphics.rectangle(
57         'fill',
58         self.position.x-self.width/2,
59         self.position.y-self.height/2,
60         self.width,
61         self.height
62         )
63     self:drawPath()
64 end
65
66 function Player:recordPosition()
67     local v = vec2:new(self.position.x, self.position.y)
68     self.position = v
69     print('Recording position for '..tostring(self)..': '..tostring(self.position))
70     local node = {}
71     node.vector = v
72     node.prev = self.path
73     self.path.next = node
74     self.path = node
75 end
76
77 function Player:multiple_keys_are_pressed()
78     local count = 0
79     for key,_ in pairs(self.keys) do
80         if love.keyboard.isDown(key) then
81             count = count + 1
82         end
83     end
84     return count > 1
85 end
86
87 function Player:update(dt)
88     if not self:multiple_keys_are_pressed() then
89         for key, name in pairs(self.keys) do
90             if love.keyboard.isDown(key)
91             and self.vector ~= self.vectors[name]
92             and (self.vector + self.vectors[name]):length() > 0
93             then
94                 self.vector = self.vectors[name]
95                 self:recordPosition()
96                 break
97             end
98         end
99     end
100     self.position:add(self.vector * self.acceleration * dt)
101 end