1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
|
-- Class: Group
-- A group is a set of sprites. Groups can be used to
-- implement layers or keep categories of sprites together.
--
-- Extends:
-- <Class>
--
-- Event: onDraw
-- Called after all member sprites are drawn onscreen.
--
-- Event: onUpdate
-- Called once each frame, with the elapsed time since the last frame in seconds.
--
-- Event: onBeginFrame
-- Called once each frame like onUpdate, but guaranteed to fire before any others' onUpdate handlers.
--
-- Event: onEndFrame
-- Called once each frame like onUpdate, but guaranteed to fire after all others' onUpdate handlers.
Group = Class:extend
{
-- Property: active
-- If false, none of its member sprites will receive update-related events.
active = true,
-- Property: visible
-- If false, none of its member sprites will be drawn.
visible = true,
-- Property: solid
-- If false, nothing will collide against this group, nor will this group
-- displace any other sprite. This does not prevent collision checking
-- against individual sprites in this group, however.
solid = true,
-- Property: sprites
-- A table of member sprites, in drawing order.
sprites = {},
-- Property: timeScale
-- Multiplier for elapsed time; 1.0 is normal, 0 is completely frozen.
timeScale = 1,
-- Property: translate
-- This table's x and y properties shift member sprites' positions when drawn.
-- To draw sprites at their normal position, set both x and y to 0.
translate = { x = 0, y = 0 },
-- Property: translateScale
-- This table's x and y properties multiply member sprites'
-- positions, which you can use to simulate parallax scrolling. To draw
-- sprites at their normal position, set both x and y to 1.
translateScale = { x = 1, y = 1 },
-- Property: gridSize
-- The size, in pixels, of the grid used for collision detection.
-- This partitions off space so that collision checks only need to do real
-- checks against a few sprites at a time. If you notice collision detection
-- taking a long time, changing this number may help.
gridSize = 50,
-- Method: add
-- Adds a sprite to the group.
--
-- Arguments:
-- sprite - <Sprite> to add
--
-- Returns:
-- nothing
add = function (self, sprite)
assert(sprite, 'asked to add nil to a group')
assert(sprite ~= self, "can't add a group to itself")
if STRICT and self:contains(sprite) then
local info = debug.getinfo(2, 'Sl')
print('Warning: adding a sprite to a group it already belongs to (' ..
info.short_src .. ' line ' .. info.currentline .. ')')
end
table.insert(self.sprites, sprite)
end,
-- Method: remove
-- Removes a sprite from the group. If the sprite is
-- not in the group, this does nothing.
--
-- Arguments:
-- sprite - <Sprite> to remove
--
-- Returns:
-- nothing
remove = function (self, sprite)
for i, spr in ipairs(self.sprites) do
if spr == sprite then
table.remove(self.sprites, i)
return
end
end
if STRICT then
local info = debug.getinfo(2, 'Sl')
print('Warning: asked to remove a sprite from a group it was not a member of (' ..
info.short_src .. ' line ' .. info.currentline .. ')')
end
end,
-- Method: collide
-- Collides all solid sprites in the group with another sprite or group.
-- This calls the <Sprite.onCollide> event handlers on all sprites that
-- collide with the same arguments <Sprite.collide> does.
--
-- It's often useful to collide a group with itself, e.g. myGroup:collide().
-- This checks for collisions between the sprites that make up the group.
--
-- Arguments:
-- other - <Sprite> or <Group> to collide with, default self
--
-- Returns:
-- boolean, whether any collision was detected
--
-- See Also:
-- <Sprite.collide>
collide = function (self, other)
other = other or self
if STRICT then
assert(other:instanceOf(Group) or other:instanceOf(Sprite), 'asked to collide non-group/sprite ' ..
type(other))
end
if not self.solid or not other.solid then return false end
local hit = false
if other.sprites then
local grid = self:grid()
local gridSize = self.gridSize
for _, othSpr in pairs(other.sprites) do
local startX = math.floor(othSpr.x / gridSize)
local endX = math.floor((othSpr.x + othSpr.width) / gridSize)
local startY = math.floor(othSpr.y / gridSize)
local endY = math.floor((othSpr.y + othSpr.height) / gridSize)
for x = startX, endX do
if grid[x] then
for y = startY, endY do
if grid[x][y] then
for _, spr in pairs(grid[x][y]) do
hit = spr:collide(othSpr) or hit
end
end
end
end
end
end
else
for _, spr in pairs(self.sprites) do
hit = spr:collide(other) or hit
end
end
return hit
end,
-- Method: displace
-- Displaces a sprite or group by all solid sprites in this group. This will *not* cause
-- any onCollide event handlers to be called.
--
-- Arguments:
-- other - <Sprite> or <Group> to collide with, default self
-- xHint - force horizontal displacement in one direction, uses direction constants, optional
-- yHint - force vertical displacement in one direction, uses direction constants, optional
--
-- Returns:
-- nothing
--
-- See Also:
-- <Sprite.displace>
displace = function (self, other, xHint, yHint)
other = other or self
if STRICT then
assert(other:instanceOf(Group) or other:instanceOf(Sprite), 'asked to displace non-group/sprite ' ..
type(other))
end
if not self.solid or not other.solid then return false end
if other.sprites then
-- group displacing group
local grid = self:grid()
local gridSize = self.gridSize
for _, othSpr in pairs(other.sprites) do
local startX = math.floor(othSpr.x / gridSize)
local endX = math.floor((othSpr.x + othSpr.width) / gridSize)
local startY = math.floor(othSpr.y / gridSize)
local endY = math.floor((othSpr.y + othSpr.height) / gridSize)
local displacers = {}
for x = startX, endX do
if grid[x] then
for y = startY, endY do
if grid[x][y] then
for _, spr in pairs(grid[x][y]) do
if spr ~= othSpr and spr.solid and spr:intersects(othSpr.x, othSpr.y, othSpr.width, othSpr.height) then
table.insert(displacers, spr)
end
end
end
end
end
end
-- see Map:subdisplace() for how this is done
if #displacers > 0 then
local hit = true
local loops = 0
while hit and loops < 3 do
hit = false
loops = loops + 1
local xVotes, yVotes = 0, 0
local minChangeX, minChangeY, absMinChangeX, absMinChangeY
local origX, origY = othSpr.x, othSpr.y
for _, spr in pairs(displacers) do
spr:displace(othSpr)
local xChange = othSpr.x - origX
local yChange = othSpr.y - origY
if xChange ~= 0 then
xVotes = xVotes + math.abs(xChange)
hit = true
if not minChangeX or math.abs(xChange) < absMinChangeX then
minChangeX = xChange
absMinChangeX = math.abs(xChange)
end
end
if yChange ~= 0 then
yVotes = yVotes + math.abs(yChange)
hit = true
if not minChangeY or math.abs(yChange) < absMinChangeY then
minChangeY = yChange
absMinChangeY = math.abs(yChange)
end
end
-- restore sprite to original position
othSpr.x = origX
othSpr.y = origY
end
if hit then
if xVotes > 0 and xVotes > yVotes then
othSpr.x = othSpr.x + minChangeX
elseif yVotes > 0 then
othSpr.y = othSpr.y + minChangeY
end
end
end
end
end
else
-- group displacing sprite
local displacers = {}
for _, spr in pairs(self.sprites) do
if spr ~= other and spr:intersects(other.x, other.y, other.width, other.height) then
table.insert(displacers, spr)
end
end
-- see Map:subdisplace() for how this is done
if #displacers > 0 then
local hit = true
local loops = 0
while hit and loops < 3 do
hit = false
loops = loops + 1
local xVotes, yVotes = 0, 0
local minChangeX, minChangeY, absMinChangeX, absMinChangeY
local origX, origY = other.x, other.y
for _, spr in pairs(displacers) do
spr:displace(other)
local xChange = other.x - origX
local yChange = other.y - origY
if xChange ~= 0 then
xVotes = xVotes + math.abs(xChange)
hit = true
if not minChangeX or math.abs(xChange) < absMinChangeX then
minChangeX = xChange
absMinChangeX = math.abs(xChange)
end
end
if yChange ~= 0 then
yVotes = yVotes + math.abs(yChange)
hit = true
if not minChangeY or math.abs(yChange) < absMinChangeY then
minChangeY = yChange
absMinChangeY = math.abs(yChange)
end
end
-- restore sprite to original position
other.x = origX
other.y = origY
end
if hit then
if xVotes > 0 and xVotes > yVotes then
other.x = other.x + minChangeX
elseif yVotes > 0 then
other.y = other.y + minChangeY
end
end
end
end
end
end,
-- Method: setEffect
-- Sets a pixel effect to use while drawing sprites in this group.
-- See https://love2d.org/wiki/PixelEffect for details on how pixel
-- effects work. After this call, the group's effect property will be
-- set up so you can send variables to it. Only one pixel effect can
-- be active on a group at a time.
--
-- Arguments:
-- filename - filename of effect source code; if nil, this
-- clears any existing pixel effect.
-- effectType - either 'screen' (applies the effect to the entire
-- group once, via an offscreen canvas), or 'sprite'
-- (applies to the effect to each individual draw operation).
-- Screen effects use more resources, but certain effects
-- need to work on the entire screen to be effective.
--
-- Returns:
-- whether the effect was successfully created
setEffect = function (self, filename, effectType)
effectType = effectType or 'screen'
if love.graphics.isSupported('pixeleffect') and
(effectType == 'sprite' or love.graphics.isSupported('canvas'))then
if filename then
self.effect = love.graphics.newPixelEffect(Cached:text(filename))
self.effectType = effectType
else
self.effect = nil
end
return true
else
return false
end
end,
-- Method: count
-- Counts how many sprites are in this group.
--
-- Arguments:
-- subgroups - include subgroups?
--
-- Returns:
-- integer count
count = function (self, subgroups)
if subgroups then
local count = 0
for _, spr in pairs(self.sprites) do
if spr:instanceOf(Group) then
count = count + spr:count(true)
else
count = count + 1
end
end
return count
else
return #self.sprites
end
end,
-- Method: die
-- Makes the group totally inert. It will not receive
-- update events, draw anything, or be collided.
--
-- Arguments:
-- none
--
-- Returns:
-- nothing
die = function (self)
self.active = false
self.visible = false
self.solid = false
end,
-- Method: revive
-- Makes this group completely active. It will receive
-- update events, draw itself, and be collided.
--
-- Arguments:
-- none
--
-- Returns:
-- nothing
revive = function (self)
self.active = true
self.visible = true
self.solid = true
end,
-- Method: contains
-- Returns whether this group contains a sprite.
--
-- Arguments:
-- sprite - sprite to look for
-- recurse - check subgroups? defaults to true
--
-- Returns:
-- boolean
contains = function (self, sprite, recurse)
if recurse ~= false then recurse = true end
for _, spr in pairs(self.sprites) do
if spr == sprite then return true end
if recurse and spr:instanceOf(Group) and spr:contains(sprite) then
return true
end
end
return false
end,
-- Method: grid
-- Creates a table indexed by x and y dimensions, with each
-- cell a table of sprites that touch this grid element. For
-- example, with a grid size of 50, a sprite at (10, 10) that
-- is 50 pixels square would be in the grid at [0][0], [1][0],
-- [0][1], and [1][1].
--
-- This can be used to speed up work that involves checking
-- for sprites near each other, e.g. collision detection.
--
-- Arguments:
-- existing - existing grid table to add sprites into,
-- optional. Anything you pass must have
-- used the same size as the current call.
--
-- Returns:
-- table
grid = function (self, existing)
local result = existing or {}
local size = self.gridSize
for _, spr in pairs(self.sprites) do
if spr.sprites then
local oldSize = spr.gridSize
spr.gridSize = self.gridSize
result = spr:grid(result)
spr.gridSize = oldSize
else
local startX = math.floor(spr.x / size)
local endX = math.floor((spr.x + spr.width) / size)
local startY = math.floor(spr.y / size)
local endY = math.floor((spr.y + spr.height) / size)
for x = startX, endX do
if not result[x] then result[x] = {} end
for y = startY, endY do
if not result[x][y] then result[x][y] = {} end
table.insert(result[x][y], spr)
end
end
end
end
return result
end,
-- passes startFrame events to member sprites
startFrame = function (self, elapsed)
if not self.active then return end
elapsed = elapsed * self.timeScale
if self.onStartFrame then self:onStartFrame(elapsed) end
for _, spr in pairs(self.sprites) do
if spr.active then spr:startFrame(elapsed) end
end
end,
-- passes update events to member sprites
update = function (self, elapsed)
if not self.active then return end
elapsed = elapsed * self.timeScale
if self.onUpdate then self:onUpdate(elapsed) end
for _, spr in pairs(self.sprites) do
if spr.active then spr:update(elapsed) end
end
end,
-- passes endFrame events to member sprites
endFrame = function (self, elapsed)
if not self.active then return end
elapsed = elapsed * self.timeScale
if self.onEndFrame then self:onEndFrame(elapsed) end
for _, spr in pairs(self.sprites) do
if spr.active then spr:endFrame(elapsed) end
end
end,
-- Method: draw
-- Draws all visible member sprites onscreen.
--
-- Arguments:
-- x - x offset in pixels
-- y - y offset in pixels
draw = function (self, x, y)
if not self.visible then return end
x = x or self.translate.x
y = y or self.translate.y
local scrollX = x * self.translateScale.x
local scrollY = y * self.translateScale.y
local appWidth = the.app.width
local appHeight = the.app.height
if self.effect then
if self.effectType == 'screen' then
if not self._canvas then self._canvas = love.graphics.newCanvas() end
self._canvas:clear()
love.graphics.setCanvas(self._canvas)
elseif self.effectType == 'sprite' then
love.graphics.setPixelEffect(self.effect)
end
end
for _, spr in pairs(self.sprites) do
if spr.visible then
if spr.translate then
spr:draw(spr.translate.x + scrollX, spr.translate.y + scrollY)
elseif spr.x and spr.y and spr.width and spr.height then
local sprX = spr.x + scrollX
local sprY = spr.y + scrollY
if sprX < appWidth and sprX + spr.width > 0 and
sprY < appHeight and sprY + spr.height > 0 then
spr:draw(sprX, sprY)
end
else
spr:draw(scrollX, scrollY)
end
end
end
if self.onDraw then self:onDraw() end
if self.effect then
if self.effectType == 'screen' then
love.graphics.setPixelEffect(self.effect)
love.graphics.setCanvas()
love.graphics.draw(self._canvas)
end
love.graphics.setPixelEffect()
end
end,
__tostring = function (self)
local result = 'Group ('
if self.active then
result = result .. 'active'
else
result = result .. 'inactive'
end
if self.visible then
result = result .. ', visible'
else
result = result .. ', invisible'
end
if self.solid then
result = result .. ', solid'
else
result = result .. ', not solid'
end
return result .. ', ' .. self:count(true) .. ' sprites)'
end
}
|