local character = require "../character" Gridwalker = class() Gridwalker.speed = 2 Gridwalker.collisionTestSize = 12 Gridwalker.neighbourOffsetX = (character.width - Gridwalker.collisionTestSize) / 2 Gridwalker.neighbourOffsetY = character.width - Gridwalker.collisionTestSize * 1.5 Gridwalker.testShape = nil Gridwalker.charinfo = nil function Gridwalker:sendKey(key) if key == "w" or key == "up" then self:up() end if key == "s" or key == "down" then self:down() end if key == "d" or key == "right" then self:right() end if key == "a" or key == "left" then self:left() end end function Gridwalker:up() local newX = self.charinfo.x local newY = self.charinfo.y - self.speed self:move(newX, newY, character.walking_up) end function Gridwalker:down() local newX = self.charinfo.x local newY = self.charinfo.y + self.speed self:move(newX, newY, character.walking_down) end function Gridwalker:right() local newX = self.charinfo.x + self.speed local newY = self.charinfo.y self:move(newX, newY, character.walking_right) end function Gridwalker:left() local newX = self.charinfo.x - self.speed local newY = self.charinfo.y self:move(newX, newY, character.walking_left) end function Gridwalker:init() self.testShape = collider:addRectangle(self.charinfo.x + self.neighbourOffsetX, self.charinfo.y + self.neighbourOffsetY, self.collisionTestSize, self.collisionTestSize) collider:setPassive(self.testShape) end function Gridwalker:setTestShape(x, y) local testX = x + self.neighbourOffsetX + self.collisionTestSize / 2 local testY = y + self.neighbourOffsetY + self.collisionTestSize / 2 self.testShape:moveTo(testX, testY) return testX, testY end function Gridwalker:move(x, y, pose) local noCollision = true local testX, testY = self:setTestShape(x, y) for other in pairs(collider:shapesInRange(testX, testY, testX + self.collisionTestSize, testY + self.collisionTestSize)) do if self.testShape:collidesWith(other) then noCollision = false break end end if noCollision then self.charinfo.x = x self.charinfo.y = y else self:setTestShape(self.charinfo.x, self.charinfo.y) end self.charinfo.pose = pose end