Bouncing box

The loop callback gets dt, the seconds since the last frame; multiplying speed by it keeps motion the same at 60 Hz and at 144 Hz. The window size is read every frame, so the box keeps its edges after a resize.


    
main.lua
local natiny = require("natiny")
local demo = require("common.modules.demo")

natiny.backend.init()

local win = natiny.window.create("Bouncing box", 900, 600)
natiny.window.set_scale_mode(win, natiny.window.SCALE_MODE_STRETCH)

local size = 80
local x, y = 100, 100
local vx, vy = 260, 190

local BG     = {  21 / 255,  30 / 255,  44 / 255 } -- #151E2C
local ACCENT = { 248 / 255, 249 / 255, 253 / 255 } -- #F8F9FD

local function frame(dt)
    natiny.window.bind(win, function()
        local w = natiny.window.get_width(win)
        local h = natiny.window.get_height(win)

        x = x + vx * dt
        y = y + vy * dt

        if x < 0 then x, vx = 0, -vx end
        if y < 0 then y, vy = 0, -vy end
        if x + size > w then x, vx = w - size, -vx end
        if y + size > h then y, vy = h - size, -vy end

        natiny.render.clear(BG[1], BG[2], BG[3], 1.0)
        natiny.render.set_color(ACCENT[1], ACCENT[2], ACCENT[3], 1.0)
        natiny.render.rectangle(x, y, size, size)
    end)
end

demo:run({
    window = win,
    title  = "Bouncing box",
    text   = "A box, a speed, and the four edges of the window",
    loop = frame,
})

natiny.backend.shutdown()