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")

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 = natiny.color.from_hex("#151E2C")
local ACCENT = natiny.color.from_hex("#F8F9FD")
natiny.backend.loop(function(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)
        natiny.render.set_color(ACCENT)
        natiny.render.rectangle(x, y, size, size)
    end)
end)

natiny.backend.shutdown()