Mothback/code/camera.lua

93 lines
2.2 KiB
Lua

Camera = {
pos = Point:new(0, 0),
width = 0,
height = 0,
speed = 4,
}
function Camera:followPlayer(player)
-- make sure we have the Point metatable self:moveTowards(pos)
local pos = Point.copy(player.pos)
local room = player:getCollidingAt(pos.x,pos.y,LoadedObjects.Rooms)
self:moveTowards(self:confineTo(room, pos))
end
function Camera:confineTo(box, pos)
if box == nil then
--frameDebug("not in a room")
return pos
end
--frameDebug("in a room")
local w = self.width/game.scale
local h = self.height/game.scale
local npos = pos - self:centerOffset()
-- bottom edge
npos.y = math.min(npos.y+h, box.to.y)-h
-- right edge
npos.x = math.min(npos.x+w, box.to.x)-w
-- top edge
npos.y = math.max(npos.y, box.from.y)
-- left edge
npos.x = math.max(npos.x, box.from.x)
return npos + self:centerOffset()
end
function Camera:confineToLevel()
self.pos.x = math.max(0,math.min(self.pos.x,LevelData.Width-self.width/game.scale))
self.pos.y = math.max(0,math.min(self.pos.y,LevelData.Height-self.height/game.scale))
end
function Camera:moveTowards(pt)
--local pt = Point:new(x,y)
local diff = pt - self:center()
local dist = diff:abs()
local npos
if dist < self.speed then
npos = pt
else
frameDebug("camera at speed limit")
npos = self:center() + diff * (self.speed/dist)
frameDebug("dist = "..dist..", npos = "..tostring(npos))
end
self:positionCenterAt(npos.x, npos.y)
end
function Camera:size()
return Point:new(self.width, self.height)
end
function Camera:centerOffset()
return self:size()/game.scale/2
end
function Camera:center()
return self.pos + self:centerOffset()
end
function Camera:positionCenterAt(x,y)
self.pos.x = x-self.width/game.scale/2
self.pos.y = y-self.height/game.scale/2
--self:ConfineToLevel()
end
function Camera:positionAt(x,y)
self.pos.x = math.floor((x/self.width)*self.width)
self.pos.y = math.floor((y/self.height)*self.height)
end
-- translate screen coordinates to game coordinates
function Camera:ptScreenToGame(pt)
return self.pos + pt
end
function Camera:mouseScreenPos()
return Point:new(love.mouse.getX(),love.mouse.getY()) / game.scale
end
-- return the mouse position as game coordinates
function Camera:mouseGamePos()
return self:ptScreenToGame(self:mouseScreenPos())
end