Skip to content

Camera, input & movement ​

clientside

Everything on this page runs in clientside scripts — weapon *.client.ts halves, clientside NPC scripts and client class halves. The server never sees the keyboard, mouse or camera: when input should change game state, the client script tells its server half with triggerServer.

It covers four things that are easiest to understand together:

  • Input — polling keys and the mouse.
  • Coordinate spaces — world tiles vs screen pixels, and converting between them.
  • The camera — following the player, or pinning it somewhere else.
  • Movement — the built-in arrow-key walking, and replacing it with your own.

Keyboard ​

keydown(key) returns whether a key is held this frame. It's a direct call that reads live input, so it's the right tool for anything continuous, like movement:

ts
export function onUpdate(delta: number) {
    if (keydown('space')) charge += delta
}

Key names are case-insensitive: 'up', 'down', 'left', 'right', letters 'a'..'z', digits '0'..'9', and named keys such as 'space', 'enter', 'escape', 'tab', 'leftshift', 'leftcontrol' or 'f1'. An unknown name just returns false.

keydown is always false while the game window is inactive and while the player is typing in the chat bar or a text field — so a hotkey never fires because someone typed the letter in chat.

Presses vs holds ​

For one-shot actions (open a menu, fire once) you want the press, not the hold. Two options:

  1. Export onKeyPressed(key) — fired once per press, never repeating while held, on every weapon, clientside NPC script and joined class, before onUpdate in the same frame. Its key names are capitalized ('T', 'Space', 'LeftShift', 'F1').

    ts
    export function onKeyPressed(key: string) {
        if (key === 'I') toggleInventory()
    }
  2. Edge-detect a keydown poll yourself, which is handy when you're already polling in onUpdate:

    ts
    let fWasDown = false
    export function onUpdate() {
        const fDown = keydown('f')
        if (fDown && !fWasDown)
            triggerServer('weapon', this.name, 'shoot', player.dir)
        fWasDown = fDown
    }

Keyboard input aimed at a focused GUI control (a text field, say) arrives as that control's keydown/keyup events instead; see GUI controls.

Mouse ​

FunctionReturns
mousex() / mousey()Cursor position in the world, in tiles (fractional), like player.x/y. Already accounts for the camera and zoom
mousescreenx() / mousescreeny()Cursor position in screen pixels, from the window's top-left. Use these for GUI and screen-mode images
mousedown(button)Whether 'left', 'right' or 'middle' is held this frame
mouseonui()Whether the cursor is over any GUI control (windows, buttons, the chat bar…)

All are direct calls returning live values. While the window is inactive the position freezes and mousedown returns false. Unlike keydown, the mouse is not disabled while the chat bar has focus.

There is no world-click event: detect clicks by edge-detecting mousedown in onUpdate, and check mouseonui() so a click on a button or window doesn't also act on the world underneath:

ts
let wasLeft = false
export function onUpdate() {
    const left = mousedown('left')
    if (left && !wasLeft && !mouseonui()) {
        const tx = Math.floor(mousex())
        const ty = Math.floor(mousey())
        triggerServer('weapon', this.name, 'clicked', tx, ty)
    }
    wasLeft = left
}

Clicks on GUI controls are better handled with the controls' own .on('click', …) events; see GUI controls. Chat bubbles don't count as UI for mouseonui.

Touch controls ​

On a touchscreen (the iOS client) there is no keyboard, so the game ships no built-in on-screen controls: your server provides them as a clientside weapon. Two pieces make that work:

FunctionWhat it does
istouchdevice()true on a touchscreen. Create your touch UI only then, so desktop players never see it
emulateKey(key, held?)Presses a key as if on the keyboard. true holds it, false releases it, no second argument taps it for one frame. Returns false for an unknown key name

An emulated key is indistinguishable from a real one: it walks the player with the built-in movement, makes keydown() return true, fires onKeyPressed, opens the chat bar with 'tab', and reaches a focused GUI control's keydown/keyup events. So the same weapons work on desktop and mobile without knowing which one they're on. It can't type characters into text fields, and like real keys it's ignored while the chat bar or a text field has focus.

ts
emulateKey('up', true)    // start walking up...
emulateKey('up', false)   // ...and stop
emulateKey('s')           // one press of S (fires onKeyPressed('S') next frame)

Held keys are released for you

A key held with emulateKey(key, true) belongs to the weapon that held it. When that weapon is removed or reloaded, or the player leaves the server, its keys are released, so a bug or a hot reload can't leave the player walking forever. emulateKey(key, false) releases the key whichever weapon held it.

The buttons themselves are ordinary GUI controls listening to touch events (touchstart, touchmove, touchend). Unlike mouse events they track every finger separately, so a player can hold the joystick and an attack button at the same time. A finger stays with the control it first touched until it's lifted, which is what a joystick needs.

This complete weapon draws a joystick in the bottom-left corner and S, D and Chat buttons in the bottom-right. Add it in the Weapons editor's Clientside tab and give it to players:

touchcontrols.client.ts
ts
// On-screen controls for touchscreens: a joystick that walks the player and
// buttons for S, D and the chat bar. Everything goes through emulateKey, so
// the built-in movement and every other weapon just see ordinary key
// presses. Nothing is created on a desktop client.

const STICK = 150        // joystick base diameter (px)
const KNOB = 56          // knob diameter
const DEADZONE = 0.3     // how far (0..1 of the radius) before a direction engages
const BUTTON = 84
const MARGIN = 24

let stick: GuiPanelCtrl | undefined
let knob: GuiPanelCtrl
let stickFinger: number | null = null
const held = new Set<string>()    // arrow keys the joystick holds right now

function buildStick() {
    stick = new GuiPanelCtrl('Touch_Stick')
    stick.extent = `${STICK},${STICK}`
    stick.color = '255,255,255,40'
    stick.bordersize = 2
    stick.bordercolor = '255,255,255,90'
    stick.borderradius = STICK / 2

    // The knob doesn't listen to touches, so fingers on it land on the base.
    knob = new GuiPanelCtrl('Touch_Knob')
    knob.extent = `${KNOB},${KNOB}`
    knob.color = '255,255,255,130'
    knob.borderradius = KNOB / 2
    stick.addControl(knob)
    steer(STICK / 2, STICK / 2)

    // Each finger has its own id; only the one that grabbed the stick steers.
    stick
        .on('touchstart', e => {
            stickFinger = e.id
            steer(e.x, e.y)
        })
        .on('touchmove', e => {
            if (e.id === stickFinger) steer(e.x, e.y)
        })
        .on('touchend', e => {
            if (e.id !== stickFinger) return
            stickFinger = null
            steer(STICK / 2, STICK / 2)   // recenter: releases every direction
        })
}

// x/y are relative to the stick's top-left and may lie outside it once the
// finger slides off — clamp to the rim.
function steer(x: number, y: number) {
    const r = STICK / 2
    let dx = x - r
    let dy = y - r
    const len = Math.hypot(dx, dy)
    if (len > r) {
        dx = dx / len * r
        dy = dy / len * r
    }
    knob.position = `${r + dx - KNOB / 2},${r + dy - KNOB / 2}`

    const want = new Set<string>()
    if (dy < -DEADZONE * r) want.add('up')
    if (dy > DEADZONE * r) want.add('down')
    if (dx < -DEADZONE * r) want.add('left')
    if (dx > DEADZONE * r) want.add('right')

    for (const key of held)
        if (!want.has(key)) emulateKey(key, false)
    for (const key of want)
        if (!held.has(key)) emulateKey(key, true)
    held.clear()
    for (const key of want) held.add(key)
}

const buttons: GuiButtonCtrl[] = []

// Holds `key` while a finger is on the button: one onKeyPressed when it
// goes down, and keydown(key) stays true for scripts that poll it.
function button(name: string, caption: string, key: string) {
    const btn = new GuiButtonCtrl(name)
    btn.text = caption
    btn.extent = `${BUTTON},${BUTTON}`
    btn.fontsize = 22
    btn.on('touchstart', () => emulateKey(key, true))
       .on('touchend', () => emulateKey(key, false))
    buttons.push(btn)
}

let laidOutW = 0
let laidOutH = 0

// Joystick bottom-left, buttons in a row bottom-right; redone when the
// screen size changes (rotation).
function layout() {
    laidOutW = ScreenWidth
    laidOutH = ScreenHeight
    stick!.position = `${MARGIN},${ScreenHeight - STICK - MARGIN}`
    buttons.forEach((btn, i) => {
        const x = ScreenWidth - (buttons.length - i) * (BUTTON + 16) - MARGIN + 16
        btn.position = `${x},${ScreenHeight - BUTTON - MARGIN}`
    })
}

export function onCreated() {
    if (!istouchdevice()) return
    buildStick()
    button('Touch_Chat', 'Chat', 'tab')
    button('Touch_Sword', 'S', 's')
    button('Touch_Fire', 'D', 'd')
    layout()
}

export function onUpdate() {
    if (stick && (ScreenWidth !== laidOutW || ScreenHeight !== laidOutH))
        layout()
}

Screen size ​

ScreenWidth and ScreenHeight are the current viewport size in screen pixels (unaffected by zoom). They're global values, not functions, but they're live: they track window resizes. Read them each time you lay something out rather than caching them in onCreated.

ts
const img = findimg(1)
img.screen = true
img.text = 'Paused'
img.style = 'c'
img.x = ScreenWidth / 2
img.y = ScreenHeight / 2

Coordinate spaces ​

The client draws in two spaces:

SpaceUnitsScrolls with the camera?Used by
Worldtiles (1 tile = 16 px)yesplayer.x/y, mousex()/mousey(), NPCs, level tiles, gettile/onwall, world-mode findimg images, projectiles
Screenpixels from the window's top-leftnomousescreenx()/mousescreeny(), ScreenWidth/Height, GUI controls, screen-mode images (img.screen = true)

The bridge between them is the camera offset and the zoom: camerax() and cameray() return the world pixel at the screen's top-left corner, and one world pixel covers player.zoomfactor screen pixels. So:

ts
// screen px -> world px -> tile (what mousex() does for the cursor)
const zoom    = player.zoomfactor
const worldPx = mousescreenx() / zoom + camerax()
const tileX   = Math.floor(worldPx / 16)

// tile -> screen px (e.g. to put a GUI marker over the player's head)
const screenX = ((player.x + 1) * 16 - camerax()) * zoom
const screenY = (player.y * 16 - cameray()) * zoom

On a gmap, the world space is the whole gmap: tiles are gmap-global (see Levels & gmaps).

Prefer world-mode images for things in the world

An image that should stay attached to something in the world (a marker over an NPC, a target reticle on a tile) is simplest as a world-mode findimg image with tile coordinates — it scrolls with the camera by itself. Convert to screen pixels only for GUI controls or screen-mode images.

The camera ​

By default the camera centers on the local player every frame (on where the player ended up after this frame's movement). It isn't clamped to the level: near the edge of a small level you'll see black beyond it.

setfocus(x, y) pins the camera so world tile (x, y) sits at the center of the screen instead — for a cutscene, a spectator view, or a map preview. resetfocus() returns it to following the player.

ts
// Pan to the town gate for three seconds.
setfocus(64, 20)
setTimeout(() => resetfocus(), 3000)
  • Both are batched calls: they apply at the next flush (by the end of the current handler at the latest). camerax() read straight after setfocus() in the same handler still returns the old offset; read it on a later frame.
  • The focus stays pinned across level changes until resetfocus().
  • When a weapon is removed from the player, the client resets the focus (so a removed weapon can't leave the camera stuck).

Zoom ​

player.zoomfactor scales the game world on this client: 1 (the default) is the unscaled view, 2 draws every world pixel as 2×2 screen pixels, so you see a quarter of the area. It's handy on large or high-resolution monitors, where the unscaled view shows a huge slice of the map and a tiny player.

ts
// Scale with the window: 1x up to 720p-ish, 2x at 1440p, 3x at 4K.
export function onCreated() {
    player.zoomfactor = Math.max(1, Math.floor(ScreenHeight / 720))
}
  • Everything in the world scales: the level, players, NPCs, world-mode images, projectiles, particles and lighting, plus name tags and chat bubbles. Text is re-rasterized at the zoomed size, so it stays crisp.
  • GUI controls and screen-mode images (img.screen = true) don't change, and neither do mousescreenx()/mousescreeny()/ScreenWidth/ScreenHeight — they stay in screen pixels. mousex()/mousey() are world tiles and already account for the zoom (see Coordinate spaces).
  • The camera still centers on the player (or the setfocus point).
  • It's clientside only: the server never sees it. It must be a finite number above 0 (anything else throws), and it's clamped to 0.25–16. It reads back immediately and applies from the next frame.
  • Whole numbers keep pixel art sharpest. Fractional zooms work, but some pixels come out a screen pixel wider than others.
  • It isn't reset when a weapon is removed; a new server connection starts back at 1.

Movement ​

Built-in movement ​

Out of the box, the arrow keys walk the local player at 6 tiles per second, resolving collision per axis (so walking diagonally into a wall slides along it) against the player's lower-body footprint, and switching between the idle and walk animations. It never stomps an animation a script started, such as a sword swing.

The position is synced to the server continuously; other players see you move and the server's player.x/y follow.

Moving the player from a script ​

Clientside, player.x, player.y and player.dir are writable. Writes are batched: any number of writes in one handler fold into a single move applied at flush, but reads see your pending writes immediately, so player.x += 1 twice moves by 2. Positions are clamped to the level bounds when the write applies.

What a write does depends on whether built-in movement is on:

  • Built-in movement enabled — the write is collision-checked per axis like a walk step: the player won't be pushed into a wall.
  • Built-in movement disabled — the write is a free teleport (still clamped to the level). Your script owns collision.

(To move a player to another level, or to teleport them authoritatively, use the serverside player.warpto.)

Custom movement ​

disabledefmovement() turns the built-in arrow-key movement off so a weapon can drive the player itself — for dashing, ice physics, grid-locked movement, vehicles. enabledefmovement() turns it back on. Both are batched. Position sync to the server keeps running either way.

A custom movement script reads keys with keydown, tests its next position with onwall on the lower-body footprint(x, y + 1, 2, 1), and writes player.x/y. For example, a minimal weapons/movement.client.ts:

ts
const SPEED = 6 // tiles/sec, same as the built-in movement

export function onCreated() {
    disabledefmovement()
}

export function onUpdate(delta: number) {
    let dx = 0, dy = 0
    if (keydown('up')) dy -= 1
    if (keydown('down')) dy += 1
    if (keydown('left')) dx -= 1
    if (keydown('right')) dx += 1
    if (dx === 0 && dy === 0) {
        if (player.ani === 'walk') setAni('idle')
        return
    }
    if (player.ani === 'idle' || player.ani === '') setAni('walk')

    // Already inside a wall (e.g. the level was edited under us)? Let the
    // player walk out instead of freezing them.
    const escaping = onwall(player.x, player.y + 1, 2, 1)

    // Per-axis, so diagonal moves slide along walls. player.x reads back the
    // pending write, so the Y test already sees the new X.
    const nx = player.x + dx * SPEED * delta
    if (escaping || !onwall(nx, player.y + 1, 2, 1)) player.x = nx
    const ny = player.y + dy * SPEED * delta
    if (escaping || !onwall(player.x, ny + 1, 2, 1)) player.y = ny

    player.dir = dy < 0 ? 'up' : dy > 0 ? 'down' : dx < 0 ? 'left' : 'right'
}

Disabling movement means owning collision

Once disabledefmovement() is active, player.x/y writes teleport. If you forget the onwall checks the player walks through walls. And don't leave both systems running: if a script moves the player and built-in movement is on, both apply every frame.

Movement comes back when the weapon goes

When a weapon is removed from the player, the client re-enables built-in movement so the player is never left unable to move. A weapon that only disables movement temporarily (a stun, a cutscene) should still call enabledefmovement() itself when it's done.

Animation names in the example assume no replacements; if your game uses replaceAni, compare against player.replacedAnis.walk ?? 'walk' — see Players.

See also ​