-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflyingenemy.lua
More file actions
65 lines (52 loc) · 1.8 KB
/
Copy pathflyingenemy.lua
File metadata and controls
65 lines (52 loc) · 1.8 KB
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
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/animation"
import "constants"
local gfx = playdate.graphics
local enemyTable = gfx.imagetable.new("images/flying_enemy")
assert(enemyTable)
if not math.clamp then
function math.clamp(val, lower, upper)
return math.min(math.max(val, lower), upper)
end
end
class("FlyingEnemy").extends(gfx.sprite)
-- Constructor
function FlyingEnemy:init(startX, y, speed, dir)
FlyingEnemy.super.init(self)
local w, h = playdate.display.getSize()
self.speed = speed * (dir == "left" and -1 or 1)
self.imgTable = enemyTable
assert(self.imgTable, "Missing flying_enemy image table!")
-- Animation
self.anim = gfx.animation.loop.new(250, self.imgTable, true)
self:setImage(self.anim:image())
self:setSize(self:getSize())
self:moveTo(startX, y)
-- Set Collission behaviour
self.collisionType = kCollisionGroupEnemy
self:setCollideRect(0, 0, self:getSize())
self:setGroups({ kCollisionGroupEnemy })
self:setCollidesWithGroups({ kCollisionGroupPlayer })
self.collisionResponse = gfx.sprite.kCollisionTypeOverlap
self:add()
end
-- Update
function FlyingEnemy:update()
self:setImage(self.anim:image())
-- Move only in x direction
local newX = self.x + self.speed
-- If we hit the edge of the screen choose whether we wrap or reverse
if newX < -self.width/2 or newX > w + self.width/2 then
if math.random() < 0.5 then
-- Ternary condition then else
newX = (newX < 0) and (w + self.width/2) or (-self.width/2)
else
-- Ternary condition then else
self.speed = -self.speed
newX = math.clamp(newX, -self.width/2, w + self.width/2)
end
end
self:moveTo(newX, self.y)
end