summaryrefslogtreecommitdiff
path: root/parallax/main.lua
blob: 6a799f404573515af96fd8ce01132c9aa9901d49 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
local boundary = {
    x = 200,
    y = 100, 
    w = 100, 
    h = 20,
}

local bg = {
    x = 200,
    y = 100, 
    w = 150, 
    h = 20
}
local p = {
    x = boundary.x + 10,
    y = boundary.y + 10,
    speed = 1,
}
local sw, sh = jin.graphics.getSize()
local canvas = jin.graphics.newCanvas(sw, sh)
function jin.core.onLoad()

end

local function clamp(x, a, b)
    return math.min(math.max(x, a), b)
end

-- keypressed
function jin.core.onEvent(e)
    if e.type == "Quit" then 
        jin.core.stop()
    end
    if e.type == "KeyDown" then 

    end 
end

local function updateBg()
    if jin.keyboard.isPressed("Escape") then 
        jin.core.stop()
    end 
    if jin.keyboard.isPressed("Left") then 
        p.x = p.x - p.speed
    end
    if jin.keyboard.isPressed("Right")then 
        p.x = p.x + p.speed
    end
    if jin.keyboard.isPressed("Up") then 
        p.y = p.y - p.speed
    end
    if jin.keyboard.isPressed("Down") then 
        p.y = p.y + p.speed
    end
    p.x = clamp(p.x, boundary.x + 20, boundary.x + boundary.w - 20)
    p.y = clamp(p.y, boundary.y + 10, boundary.y + boundary.h - 10)

    local x0 = boundary.x
    local x1 = boundary.x + boundary.w
    local tx = (p.x - x0) / (x1 - x0)
    bg.x = tx * (x1 - x0 - bg.w) + x0
    local y0 = boundary.y
    local y1 = boundary.y + boundary.h
    local ty = (p.y - y0) / (y1 - y0)
    bg.y = ty * (y1 - y0 - bg.h) + y0
end

function jin.core.onUpdate(dt)
    updateBg()
end

function jin.core.onDraw()
    jin.graphics.bindCanvas(canvas)
    jin.graphics.clear()
    jin.graphics.setColor(100, 100, 100, 255)
    jin.graphics.rect("fill", bg.x, bg.y, bg.w, bg.h)
    jin.graphics.setColor(255,255,255,255)
    jin.graphics.rect("line", boundary.x, boundary.y, boundary.w, boundary.h)
    jin.graphics.setColor(255,0,0,255)
    jin.graphics.rect("fill", p.x - 2, p.y- 2, 4, 4)
    jin.graphics.setColor(0, 255, 0)
    jin.graphics.rect("line", p.x - 20, p.y - 10, 40, 20)
    jin.graphics.unbindCanvas()
    jin.graphics.setColor(255, 255, 255)
    jin.graphics.draw(canvas, 0, 0)
end