Input and text

Move the mouse, hold the left button, press W A S D. The font is fetched from data/common/fonts/roboto.ttf - scripts run in the browser, assets stay put.

Click the canvas first so it takes keyboard focus.


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

natiny.backend.init()

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

-- The face is a file like any other: the shell fetches it and hands it over
-- once it is here, sized for this demo.
local font

local KEY_W, KEY_A = natiny.input.KEY_W, natiny.input.KEY_A
local KEY_S, KEY_D = natiny.input.KEY_S, natiny.input.KEY_D

local x, y = 450, 300
local speed = 320

local BG     = {  21 / 255,  30 / 255,  44 / 255 } -- #151E2C
local OBJECT = { 169 / 255, 179 / 255, 197 / 255 } -- #A9B3C5
local ACCENT = { 248 / 255, 249 / 255, 253 / 255 } -- #F8F9FD
local LIGHT_TEXT = { 243 / 255, 245 / 255, 250 / 255 } -- #F3F5FA

local function frame(dt)
    natiny.window.bind(win, function()
        if natiny.input.get_key_down(KEY_W) then y = y - speed * dt end
        if natiny.input.get_key_down(KEY_S) then y = y + speed * dt end
        if natiny.input.get_key_down(KEY_A) then x = x - speed * dt end
        if natiny.input.get_key_down(KEY_D) then x = x + speed * dt end

        local mx = natiny.input.get_mouse_x()
        local my = natiny.input.get_mouse_y()
        local held = natiny.input.get_mouse_button_down(natiny.input.MOUSE_BUTTON_LEFT)

        natiny.render.clear(BG[1], BG[2], BG[3], 1.0)

        -- the player square
        natiny.render.set_color(ACCENT[1], ACCENT[2], ACCENT[3], 1.0)
        natiny.render.rectangle(x - 20, y - 20, 40, 40)

        -- a cursor that reacts to the left button
        if held then
            natiny.render.set_color(ACCENT[1], ACCENT[2], ACCENT[3], 1.0)
        else
            natiny.render.set_color(OBJECT[1], OBJECT[2], OBJECT[3], 1.0)
        end
        natiny.render.circle(mx, my, held and 26 or 14)

        natiny.render.set_color(LIGHT_TEXT[1], LIGHT_TEXT[2], LIGHT_TEXT[3], 1.0)
        natiny.render.text(font, 20, 550, "WASD to move, click to grow the dot")
    end)
end

demo:run({
    window = win,
    title  = "Input",
    text   = "WASD moves the square, the left button grows the dot",
    resources = { "data/common/fonts/roboto.ttf" },

    on_loaded = function()
        font = natiny.font.create(demo:resource("data/common/fonts/roboto.ttf"), 22)
    end,

    loop = frame,
})

natiny.backend.shutdown()