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
|
local Enemy = {}
local Entity = require("entity")
Enemy.__index = Enemy
setmetatable(Enemy, { __index = Entity })
function Enemy.new(spawnX, spawnY, width, height, physicsWidth, physicsHeight)
local self = setmetatable(Entity:new(spawnX or 0, spawnY or 0, width or 16, height or 16, physicsWidth or width or 8, physicsHeight or height or 8), Enemy)
self.isEnemy = true
self.texture = love.graphics.newImage("assets/misc/enemy.png")
self.texture:setFilter("nearest", "nearest")
self.direction = math.random(1, 2) == 1 and 1 or -1
self.facing = self.direction
self.speed = 20
self.turnDelay = 1
self.turning = false
self.turnTimer = 0
return self
end
function Enemy:setWorldContext(world)
self.world = world
self:enablePhysics(world.physicsWorld, "dynamic")
end
function Enemy:noPathAhead()
if not self.world then return false end
local frontX
if self.direction == 1 then
frontX = self.x + self.physicsWidth * 1.5 + 1
else
frontX = self.x + self.physicsWidth * 0.5 - 1
end
local midY = self.y + self.physicsHeight * 0.5
local belowY = self.y + self.physicsHeight + 1
local wallAhead = self.world:isTileSolidAtPixel(frontX, midY)
local floorAhead = self.world:isTileSolidAtPixel(frontX, belowY)
return wallAhead or not floorAhead
end
function Enemy:patrolPlatform(dt)
self:syncFromPhysicsBody()
if self.turning then
self.turnTimer = self.turnTimer - dt
if self.turnTimer <= 0 then
self.direction = self.direction * -1
self.turning = false
end
if self.body then
local _, vy = self.body:getLinearVelocity()
self.body:setLinearVelocity(0, vy)
end
return
end
if self:noPathAhead() then
self.turning = true
self.turnTimer = self.turnDelay
end
self.facing = self.direction
if self.body then
local _, vy = self.body:getLinearVelocity()
self.body:setLinearVelocity(self.speed * self.direction, vy)
end
end
function Enemy:update(dt)
self:patrolPlatform(dt)
end
function Enemy:draw()
local tw = self.texture:getWidth()
local th = self.texture:getHeight()
local sx = (self.facing == -1) and -1 or 1
local cx = self.x + self.physicsWidth
local cy = self.y + self.physicsHeight /2
love.graphics.draw(self.texture, cx, cy, 0, sx, 1, tw / 2, th / 2)
end
return Enemy
|