9 scene.width = love.graphics.getWidth()
10 scene.height = love.graphics.getHeight()
13 scene.grid.bgcolor = {0.2, 0.2, 0.5}
14 scene.grid.linecolor = {0.3, 0.3, 0.6}
19 table.insert(scene.players, require('players/1'))
20 --table.insert(scene.players, require('players/2'))
24 function scene:drawGrid()
25 love.graphics.setBackgroundColor(self.grid.bgcolor)
26 love.graphics.setColor(self.grid.linecolor)
28 for x=0,self.width,self.grid.delta do
29 love.graphics.line(x, 0, x, self.height)
31 for y=0,self.height,self.grid.delta do
32 love.graphics.line(0, y, self.width, y)
36 function scene:drawPlayers()
37 for _,player in pairs(self.players) do
46 -- draw intersection if it's there
47 if self.intersection then
48 love.graphics.setColor(0, 255, 0)
49 love.graphics.line(self.intersection.a)
50 love.graphics.setColor(0, 0, 255)
51 love.graphics.line(self.intersection.b)
56 function scene:updatePlayers(dt)
57 for _,player in pairs(self.players) do
62 function doLinesIntersect(x1,y1, x2,y2, x3,y3, x4,y4)
63 if x1 == x2 and x3 == x4
64 or y1 == y2 and y3 == y4
66 -- if lines are parallel, no intersection!
69 -- if lines are not parallel, they must intersect
70 -- do segments overlap?
73 (x1 <= x3 and x3 <= x2 or x1 <= x4 and x4 <= x2)
75 (x3 <= x1 and x1 <= x4 or x3 <= x2 and x2 <= x4)
77 (y1 <= y3 and y3 <= y2 or y1 <= y4 and y4 <= y2)
79 (y3 <= y1 and y1 <= y4 or y3 <= y2 and y2 <= y4)
83 scene.intersection = {
92 function doesLineIntersectPlayerPaths(path, x1,y1, x2,y2)
96 -- for every line in path,
97 -- check intersection with player line
98 for k,v in pairs(path) do
100 if #cache.b == 2 then
101 if doLinesIntersect(x1,y1, x2,y2, cache.a[1],cache.a[2], cache.b[1],cache.b[2]) then
108 table.insert(cache.a,v)
113 -- love collision handler
114 function collision(player)
115 print('Player '..tostring(player)..' crashed!')
118 love.handlers.collision = collision
120 function scene:handleCollisions()
121 -- calculate the last line for each player from current position
122 -- check if line intersects any other path line
123 -- if so, raise collision event for player
124 for _,player in pairs(self.players) do
125 local x1 = player.path[#player.path-1]
126 local y1 = player.path[#player.path]
127 local x2 = player.position.x
128 local y2 = player.position.y
130 -- check intersection against each existing path
131 for _,player2 in pairs(self.players) do
132 if doesLineIntersectPlayerPaths(player2.path, x1, y1, x2, y2) then
133 love.event.push('collision', player)
139 function scene:update(dt)
140 self:updatePlayers(dt)
141 self:handleCollisions()
145 function scene:quit()
146 for _,player in pairs(self.players) do
147 print(tostring(player)..' generated '.. #player.path / 2 .. ' path points')