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