summaryrefslogtreecommitdiff
path: root/objects/Door.lua
blob: 343b2c3b30aab0601e5c281df0b1da2fe4af60b8 (plain)
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
require "data.directions"
local audio = require "utils.audio"

local Door = {}
Door.__index = Door

local function calculateDoorLocation(obj)
    local roomX, roomY = obj.within:getX(), obj.within:getY()
    local roomW, roomH = obj.within:getWidth(), obj.within:getHeight()
    local loc, size, thickness = obj.location, obj.size, obj.thickness

    local positions = {
        [Direction.LEFT]   = { x = roomX, y = (love.graphics.getHeight() - size) / 2, w = thickness, h = size },
        [Direction.RIGHT]  = { x = roomX + roomW, y = (love.graphics.getHeight() - size) / 2, w = thickness, h = size },
        [Direction.TOP]    = { x = (love.graphics.getWidth() - thickness) / 2, y = roomY, w = size, h = thickness },
        [Direction.BOTTOM] = { x = (love.graphics.getWidth() - thickness) / 2, y = roomY + roomH, w = size, h = thickness }
    }

    local pos = positions[loc]
    obj.x, obj.y, obj.w, obj.h = pos.x, pos.y, pos.w, pos.h
end

function Door:new(location, within, to)
    local obj = {
        objectType = "door",
        location = location,
        size = config.graphics.doorSize,
        thickness = config.graphics.doorThickness,

        within = within,
        to = to,
    }

    setmetatable(obj, Door)

    calculateDoorLocation(obj)

    return obj
end

function Door:setTo(room)
    self.to = room
end

function Door:onContact(other)
    local map = require "logic.map"
    if other.objectType == "player" then
        if not G.currentRoom.isCleared then return end

        map.switchRoom(self.to)

        -- update player position after entering a new room
        local doorH, doorW, playerR = self.h, self.w, G.player.physicsShape:getRadius()
        local roomX, roomY, roomW, roomH = G.currentRoom:getX(), G.currentRoom:getY(), G.currentRoom:getWidth(), G.currentRoom:getHeight()

        local positions = {
            [Direction.LEFT]   = { "x", roomX + roomW - playerR - doorW },
            [Direction.RIGHT]  = { "x", roomX + playerR + doorW },
            [Direction.TOP]    = { "y", roomY + roomH - playerR - doorH },
            [Direction.BOTTOM] = { "y", roomY + playerR + doorH }
        }

        local axis, pos = positions[self.location][1], positions[self.location][2]
        G.BodyLifeCycleManager:setPosition(G.player, axis, pos)

        audio.play("door")
    end
end

return Door