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

natiny.backend.init()

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

local font_resource = natiny.resource.load("common/fonts/roboto.ttf")
local font = natiny.font.create(font_resource, 22)
natiny.resource.destroy(font_resource)

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 = natiny.color.from_hex("#151E2C")
local OBJECT = natiny.color.from_hex("#A9B3C5")
local ACCENT = natiny.color.from_hex("#F8F9FD")
local LIGHT_TEXT = natiny.color.from_hex("#F3F5FA")
natiny.backend.loop(function(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)

        -- the player square
        natiny.render.set_color(ACCENT)
        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)
        else
            natiny.render.set_color(OBJECT)
        end
        natiny.render.circle(mx, my, held and 26 or 14)

        natiny.render.set_color(LIGHT_TEXT)
        natiny.render.text(font, 20, 550, "WASD to move, click to grow the dot")
    end)
end)

natiny.backend.shutdown()