cenker's mod - Manual

Version 2.5.7

A multiplayer game that hosts multiple mini-games and enables community mod creation

Copyright ยฉ 2023-Present DurmuลŸ Cenker Cennet (cenullum)
https://www.cenullum.com

cenker's mod is built with Godot Engine, Lua 5.4, and Weasel Games Godot Lua API.

๐Ÿ’พ Offline Access: Please download this manual from your browser (Save Page As) to access it offline while modding.
๐Ÿ’ก LSP/Code Completion Support: The file cenkers_mod_stub.lua (included in every mod folder) contains detailed API type definitions and documentation comments for all available functions. You can use this file with external editors that support luaLSP for features like code suggestions and code completion, as there is currently no built-in LSP support in cenker's mod.

1. Introduction

Important: cenker's mod is not a game engine. It is a package that has multiple multiplayer mods within it. Users can create and host their own mods using Lua 5.4 scripting. cenker's mod handles networking, physics, rendering, and input management, allowing you to focus on creating unique experiences.

Lua Environment: The game uses Lua 5.4 with the following standard libraries available:
  • base - Basic functions (print, type, pairs, ipairs, etc.)
  • table - Table manipulation
  • string - String operations
  • math - Mathematical functions
Other Lua libraries (io, os, debug, etc.) are NOT available for security reasons. Use the provided API functions instead (e.g., get_os_time() for time, save_json() for file I/O).

Key Features

Example Mods

The game comes with three example mods that demonstrate different gameplay styles:

2. Getting Started

Mod Structure

Each mod follows this directory structure:

mods/YourModName/
โ”œโ”€โ”€ general/
โ”‚   โ”œโ”€โ”€ scripts/          # Lua entity scripts
โ”‚   โ”‚   โ”œโ”€โ”€ user.lua     # Player entity (required)
โ”‚   โ”‚   โ”œโ”€โ”€ world.lua    # World singleton (recommended)
โ”‚   โ”‚   โ””โ”€โ”€ ...          # Your custom entities
โ”‚   โ”œโ”€โ”€ images/          # PNG textures
โ”‚   โ””โ”€โ”€ sounds/          # OGG audio files
โ”œโ”€โ”€ maps/                # Tilemap definitions
โ””โ”€โ”€ cenkers_mod_stub.lua # API type definitions (optional)
Note: The user.lua script is mandatory for player entities. The world.lua singleton is recommended for managing game state.

Your First Entity

Create a simple entity in general/scripts/my_entity.lua:

Variable Declaration Rules: Variables at the top of the script (before any function, comment, or blank line) must be primitive types (numbers, strings, booleans). These special configuration variables are parsed before script execution. See the list of special variables below.
-- Set entity properties at the top (MUST be primitive values)
network_mode = 2  -- DYNAMIC: synced continuously
z_index = 5       -- Rendering order (must be between -999 and 999)

-- Called every frame
function _process(delta, inputs)
    -- Your game logic here
    if IS_LOCAL then
        -- Only execute on local player's machine
    end

    if IS_HOST then
        -- Only execute on host machine
    end

    return inputs
end

-- Initialize entity
set_image({
    parent_name = name,
    name = "my_sprite",
    image_path = "my_texture",  -- loads my_texture.png
    scale = Vector2(32, 32)
})

set_collision({
    parent_name = name,
    shape = "circle",
    size = 16
})

3. Game Architecture

3.1 Entities

Entities are the fundamental building blocks of your game. Each entity is a Lua script that defines behavior and properties. The game automatically creates a RigidBody2D node for each entity.

Entity Global Scope: Each entity has its own separate global Lua environment. Variables declared without local are global to that entity only. There is no shared global table (_G) between entities - each entity's globals are isolated from other entities.
Important Physics Limitations:
  • Maximum velocity for any entity is 600 (linear velocity magnitude is capped)
  • Z-index values must be between -999 and 999

Entity Properties

Property Type Description Default
network_mode integer 0=NONE (local), 1=STATIC (sync on join), 2=DYNAMIC (continuous sync) 0
speed number Movement speed multiplier 15
jump_force number Jump impulse force (side-scroller only) 500
max_jump_count integer Total jumps allowed (negative = infinite,0 = disabled, 1 = single, 2 = double ) 2
wall_jump_enabled boolean Enable jumping away from walls true
mass number Physics mass 1
gravity_scale number Gravity multiplier (0.0 = no gravity) 0.0
linear_damp number Movement friction 1.0
bounce number Bounciness (0.0-1.0) 0
friction number Surface friction 1

Example: Football Player

-- From Football mod: user.lua
bounce = 0.8
friction = 0.1
lock_rotation = true

add_tag(name, "user")

function _process(delta, inputs)
    -- Handle player input
    if inputs["key_7"] then
        hit_value = math.min(hit_value + 100*delta, 100)
    end
    return inputs
end

3.2 Singletons

Singletons are special entities that exist once per game and manage global state. They are prefixed with - and short names are recommended for network efficiency.

-- Define as singleton at the top of your script
singleton_name = "-game_manager"

-- Singletons are accessible from any entity
run_function("-game_manager", "start_game", {})
Best Practice: Use short singleton names (like -gm, -ui) to reduce network traffic.

3.3 Network Modes

Network synchronization is controlled by the network_mode variable:

Mode Value Description Use Case
NONE 0 Local only, not synchronized Client-side UI, visual effects
STATIC 1 Synchronized only when players join. Movement is NOT synced. Static world objects, decorations that don't move
DYNAMIC 2 Continuously synchronized. Position, rotation, and velocity are synced automatically. Players, projectiles, moving objects
Security Warning: ALL variables in STATIC (1) and DYNAMIC (2) entities are sent from host to clients when players join. This includes all script variables. Be careful with sensitive data - store it in non-networked entities or use local-only variables (declared with local).
Note: DYNAMIC entities automatically sync position, rotation, and linear velocity. STATIC entities stay in place and don't sync movement.

Network Functions

Network functions use suffixes to control execution:

Suffix Who Can Call Where It Runs without Specific Steam ID Where It Runs with Specific Steam ID as last parameter
_HOST Host or client Host Only Nothing happens
_ALL Host Only All Clients (Including Host) Function will only run on host and the specific user
_CLIENT Host Only All Clients (Excluding Host) Function will only run on specific user( specific user can be host itself)
Critical Requirements for Network Functions:
  • Function name MUST end with _HOST, _ALL, or _CLIENT
  • First parameter MUST be named sender_id (or similar; it is a string representing the Steam ID of who wants to run the function)
  • If entity_name is "user", the function will work on each user entity once
  • Network functions without these suffixes will NOT work
function my_function_HOST(sender_id, other_params)
    -- sender_id is the Steam ID of who called this
end
Security Rule: Always validate player actions on the host before applying them! Clients should only send requests, and the host should validate and execute the actual game logic to prevent cheating.

Network Function Examples

Example 1: Simple Weapon System

-- BAD: Client directly modifies gameplay
function fire_weapon()
    if IS_LOCAL then
        spawn_entity_local({t = "bullet"})  -- Client can cheat!
    end
end

-- GOOD: Client requests, host validates
function fire_weapon()
    if IS_LOCAL then
        run_network_function(name, "request_fire_weapon_HOST", {})
    end
end

function request_fire_weapon_HOST(sender_id)
    if sender_id ~= name then return end  -- Verify sender

    -- Check cooldown using Unix time (seconds)

    local current_time = get_os_time()  -- Returns Unix timestamp in seconds
    if current_time - last_fire_time < 1 then return end  -- 1 second cooldown

    last_fire_time = current_time

    -- Spawn on host
    spawn_entity_host({
        t = "bullet",
        p = get_value("", sender_id, "position"),
        owner = sender_id
    })
end

Example 2: Hook System (from Hook Up Mod)

-- From Hook Up mod: user.lua
-- Client requests to fire hook
function fire_hook_to_mouse()
    if IS_LOCAL then
        run_network_function(name, "request_fire_hook_HOST", {hook_power})
    end
end

-- Host validates and processes the request
function request_fire_hook_HOST(sender_id, requested_power)
    if sender_id ~= name then return end  -- Validate sender

    if hook_state ~= "READY" then return end  -- Validate state

    -- Clamp power to prevent cheating
    local clamped_power = math.max(hook_power_min,
                                   math.min(requested_power, hook_power_max))

    -- Calculate and apply velocity
    local direction = (mouse_position - position).normalized()
    local velocity = direction * clamped_power

    unfreeze_entity(hook_entity_name, true)
    change_instantly({
        entity_name = hook_entity_name,
        linear_velocity = velocity,
        position = position
    })

    -- Sync state to all clients
    run_network_function(sender_id, "set_hook_state_ALL", {"FIRING"})
end

-- All clients update their hook state
function set_hook_state_ALL(sender_id, new_state)
    hook_state = new_state

    if new_state == "FIRING" then
        run_function(hook_entity_name, "activate_hook", {})
        if IS_LOCAL then
            set_camera_target(hook_entity_name)
        end
    end
end

4. Lua API Reference

4.1 Global Variables

These variables are automatically available in every entity script:

Variable Type Description
name string Unique entity name (for users, this is their Steam ID)
script_name string Script filename without .lua extension
position Vector2 Current world position
rotation number Current rotation in radians
linear_velocity Vector2 Current movement velocity
IS_LOCAL boolean True if this is the local player's entity
IS_HOST boolean True if running on host machine (on a dedicated server: the server process, which has no player)
IS_DEDICATED boolean True on a dedicated server and on every player connected to one. See 4.16
LOCAL_STEAM_ID string Local player's id, as a string: their Steam ID (17 digits), or their local user id (15 digits) when they joined without Steam. On a dedicated server it has no entity - check entity_exists(LOCAL_STEAM_ID)
HOST_STEAM_ID string Host's id. On a dedicated server it is the server, never a player - use is_admin(id) for "may do host things"
MOD_PATH string Absolute path to current mod directory
Performance Tip - Direct Variable Access: For certain built-in variables like position, rotation, linear_velocity, and angular_velocity, you can read them directly by name without using get_value(). However, you MUST still use set_value() when modifying them so the game can detect and process the changes.
-- Reading: Direct access is faster
local pos = position  -- Instead of get_value("", name, "position")
local vel = linear_velocity  -- Instead of get_value("", name, "linear_velocity")

-- Writing: Must use set_value() for game to detect changes
set_value("", name, "position", Vector2(100, 200))
set_value("", name, "linear_velocity", Vector2(50, 0))

4.2 Callback Functions

Define these functions in your entity to receive events:

_process(delta, inputs)

Called every frame. Return modified inputs dictionary or nil.

Performance Warning: _process runs every frame and consumes significant processing power. Avoid calling expensive functions like set_label, set_image, or set_progress_bar inside _process unless values actually change. Cache previous values and only update UI when needed.
function _process(delta, inputs)
    -- delta: time since last frame in seconds
    -- inputs: table with the following keys:
    --   key_1 to key_13: boolean (various buttons, see input table below)
    --   stick_1: Vector2  -- left stick / WASD (movement)
    --   stick_2: Vector2  -- right stick / mouse position in world space

    if IS_LOCAL then
        -- Check input
        if inputs["key_6"] then  -- Interact key (E / Square / Y)
            -- Perform action
        end

        -- Movement using stick_1
        local movement = inputs["stick_1"]
        if movement.x ~= 0 or movement.y ~= 0 then
            -- Apply movement
        end
    end

    return inputs  -- or nil to leave unchanged
end

Input System and Gamepad Support

The game comes with full gamepad integration and virtual mouse support. Players can use keyboard/mouse, Nintendo Switch controllers, Xbox controllers, or PlayStation controllers. The input mappings are automatically handled by the game.

Modder-Friendly Input System: Players can customize their key bindings in the game settings. As a modder, you don't need to do anything special - just use the input names (key_1 through key_13, stick_1, stick_2) and the game handles the rest. For detailed gamepad mappings, refer to gamepad.ods in the docs folder.
Input Name Default PC Key Xbox PlayStation Nintendo Switch Suggested Use
key_1 1 D-Pad Right D-Pad Right D-Pad Right Item selection
key_2 2 D-Pad Left D-Pad Left D-Pad Left Item selection
key_3 3 D-Pad Down D-Pad Down D-Pad Down Item selection
key_4 Q D-Pad Up D-Pad Up D-Pad Up Switch previous item
key_5 R Y Triangle X Reload
key_6 E X Square Y Interact
key_7 F B Circle A Dash
key_8 SPACE A X B Jump
key_9 RIGHT MOUSE LB L1 L Secondary fire/action
key_10 SHIFT LT L2 ZL Sprint
key_11 G L3 (Left Stick Click) L3 (Left Stick Click) L3 (Left Stick Click) Drop
key_12 LEFT MOUSE RB R1 R Primary fire/action
key_13 CTRL RT R2 ZR Crouch
stick_1 WASD Left Stick Left Stick Left Stick Movement controls
stick_2 Mouse Position Right Stick Right Stick Right Stick Mouse position in world space
Note: Some inputs like ESC (Select, Back, Share button to open in-game menu), SPACE (Start, Menu, Options for UI selection), and R3 (virtual mouse click) are reserved for system use as default keybinds and cannot be listened to by modders. The game also features a virtual mouse system that allows gamepad users to interact with UI elements seamlessly.

Virtual Gamepad (touch screens)

On phones and tablets the game shows an on-screen gamepad while you play (players can switch it on for a PC too, under Settings → Virtual Gamepad, and drag every button where they like). It does not add new inputs: each on-screen control is one of the inputs in the table above, and it reaches your _process(delta, inputs) exactly like a key press would.

_on_user_initialized(steam_id, nickname)

Called when a user finishes joining and is ready to receive network calls.

function _on_user_initialized(steam_id, nickname)
    if IS_HOST then
        if steam_id == name then
            -- This user just finished initializing
            local player_color = generate_random_color()
            run_network_function(name, "create_user_ALL", {player_color})
        else
            -- Send existing data to new player
            run_network_function(name, "sync_state_CLIENT", {current_state}, steam_id)
        end
    end
end

_on_user_disconnected(steam_id, nickname)

Called when a user leaves the game.

function _on_user_disconnected(steam_id, nickname)
    if steam_id == name then
        -- Clean up this user's entities
        destroy("", hook_entity_name)
        destroy_line(hook_line_name)
    end
end

add_command(entity_name, function_name, command_name, description, chat_executable)

Registers a command to the centralized command system. Commands are reset when the map is unloaded. Note: Do not include the / prefix in the command_name; it is added automatically for chat.

Important: add_command cannot execute network functions directly via run_network_function. If you need to trigger network logic from a command, you must use a local intermediate (wrapper) function as the callback, which then calls run_network_function.
-- Typical usage (at top of script)
add_command("-cmd", "show_rules", "rules", "Shows Finding Liar game rules", true)
-- Users can now type '/rules' in chat or 'rules' in the console.

-- Callback function example:
function show_rules(sender_id, arg1, arg2)
    -- arg1, arg2 etc. are strings passed from the chat/console
    add_to_chat("Rules: Be nice!", false)
end

_on_chat_message_received(sender_id, nickname, message)

Called when a chat message is received. Supports chaining between multiple mods.

Automatic Command Interception: The system now checks for mod commands (registered via add_command) before calling this function. If a message matches a registered command, this handler will not be triggered for that message.
Pre-formatted Message: The message argument is already formatted with the player's nickname and color (e.g., [color=#66FF99]username[/color]: actual message).
Chaining Logic:
  • Return nil: Mod performs no action. Passes the current message to the next mod.
  • Return "": Mod suppresses the message. The chain stops, and nothing is displayed.
  • Return string: Mod modifies the message. The new string is passed to the next mod.
function _on_chat_message_received(sender_id, nickname, message)
    -- Example 1: Suppress messages from a specific user
    if sender_id == "76561198..." then
        return "" 
    end

    -- Example 2: Profanity Filter (Censorship)
    -- Replaces "your mom" with "***" (case-insensitive)
    local censored_message = message:gsub("[Yy][Oo][Uu][Rr] [Mm][Oo][Mm]", "***")

    -- Example 3: Emoji Replacement
    -- Replaces ":)" with a smiling face symbol
    local final_message = censored_message:gsub(":%s?%)", "๐Ÿ˜Š")

    -- Example 4: Add a custom prefix
    return "[GLOBAL] " .. final_message
end

_on_gamepad_connection_changed(has_gamepad)

Called when gamepad is connected/disconnected or display style changes.

function _on_gamepad_connection_changed(has_gamepad)
    if IS_LOCAL then
        -- Refresh button prompts
        set_label({
            name = "tutorial_label",
            text = "Press @key_7@ to interact\n@stick_1@ to move"
        })
    end
end

_on_navigation_finished(reached)

Called on an entity moved with navigate_to when it stops on its own: true when it reached the target, false when there is no path or it got stuck. Not called when you stop it yourself. See 4.14 Pathfinding.

4.3 Entity Management

spawn_entity_local(config)

Spawn an entity locally (client-side only, not synced).

-- Spawn a local particle effect
local particle = spawn_entity_local({
    t = "particle_effect",      -- script name
    p = Vector2(100, 100),      -- position
    r = 0,                      -- rotation in radians
    v = Vector2(0, 0),          -- linear velocity
    a = 0,                      -- angular velocity
    -- Custom properties:
    duration = 2.0,
    color = Color(1, 0, 0, 1)
})

spawn_entity_host(config)

Spawn a network-synchronized entity (Host only).

-- From Campfire Survivors: spawn monsters
if IS_HOST then
    local monster = spawn_entity_host({
        t = "monster",
        p = spawn_position,
        hp = 100,
        damage = 10,
        speed = 20
    })
end

destroy(parent_name, entity_name, notify_network)

Destroy an entity and its children.

-- Destroy a networked entity
if IS_HOST then
    destroy("", bullet_name, true)  -- Notify clients
end

-- Destroy a local entity
destroy("", effect_name, false)

entity_exists(entity_name, parent_name)

Ask whether an entity - or one of its children, such as an image or a label - is still in the world, without logging an error when it is not. Every other lookup (get_value, set_image, set_shader...) prints an error for a missing entity, which is what you want for a typo but not for something that legitimately outlives its target: a timer, or a hit flash still playing on the monster the killing blow just destroyed. Without this guard those few frames fill the log with identical errors.

if entity_exists(monster_name) then
    run_function(monster_name, "take_damage", { 10 })
end

-- Checking a child: pass the parent as the second argument.
if entity_exists("body", monster_name) then
    set_shader({ parent_name = monster_name, image_name = "body", shader_name = "" })
end

freeze_entity(entity_name, all)

Freeze an entity's physics (stops movement).

-- From Hook Up: freeze hook when attached
freeze_entity(hook_entity_name, true)  -- Sync to all clients

4.4 Network Functions

run_network_function(entity_name, function_name, parameters, steam_id)

Execute a function across the network.

-- Host broadcasts to all clients
if IS_HOST then
    run_network_function("user_steam_id", "update_score_ALL", {new_score})
end

-- Client sends request to host
if IS_LOCAL then
    run_network_function(name, "request_action_HOST", {action_data})
end

-- Host sends to specific client
if IS_HOST then
    run_network_function(name, "show_message_CLIENT",
                        {"Welcome!"}, target_steam_id)
end

Important: User Entity Names Are Steam IDs

In user scripts (user.lua), the name variable contains the player's Steam ID. This is why callbacks like _on_user_initialized, _on_user_disconnected, and _on_user_banned often check if steam_id == name - these callbacks run on ALL user entities, so you need to verify which user the event belongs to.

-- These callbacks run on EVERY user entity
function _on_user_disconnected(steam_id, nickname)
    if steam_id == name then  -- Check if THIS user disconnected
        -- Clean up this user's entities
        destroy("", hook_entity_name)
        stop_timer("shoot_timer"..name)
    end
end

function _on_user_initialized(steam_id, nickname)
    if steam_id == name then  -- Check if THIS user just joined
        -- Initialize this user
        run_network_function(name, "setup_player_ALL", {})
    end
end

Targeting User Entities: When calling network functions on user entities, use the player's Steam ID as the entity name:

-- target_steam_id is a specific player's Steam ID
run_network_function(target_steam_id, "change_team_ALL", {team_id})

-- In the user.lua script, 'name' equals the Steam ID
run_network_function(name, "update_health_ALL", {new_health})

4.5 UI System

create_panel(config)

Create a custom UI window/panel.

-- From Hook Up: inventory panel
local panel_name = create_panel({
    name = "_inventory_panel",
    title = "Inventory",
    text = "Your items:",
    resizable = true,
    close = true,
    minimum_size = Vector2(400, 300),
    is_scrollable = true,
    color = Color(0.2, 0.2, 0.2, 0.9)
})

add_button_to_panel(panel_name, config)

Add an interactive button to a panel.

add_button_to_panel("_upgrade_panel", {
    entity_name = name,
    function_name = "select_upgrade",
    text = "Increase Speed (+20%)",
    extra_args = {upgrade_type = "speed", value = 0.2},
    color = Color(0.3, 0.5, 0.7)
})

set_label(config)

Create or update a text label.

-- From Campfire Survivors: health display
if IS_LOCAL then
    set_label({
        name = "_health_label",
        text = string.format("Health: %d/%d", current_health, max_health),
        position = Vector2(20, 20),
        size = Vector2(200, 20),
        font_size = 16,
        font_color = Color(1, 1, 1, 1),
        outline_size = 2,
        outline_color = Color(0, 0, 0, 1)
    })
end

Crisp world-space text (font_size + scale)

Small font sizes render blurry on world-space labels (name tags, damage numbers). Instead, pick a big font_size and shrink the label with the scale config (a float scales uniformly, or pass a Vector2). Set it once — there is no per-frame cost. Note that position and size are pre-scale: a 384×72 label at scale 0.25 covers 96×18 world pixels. The same Scale setting is available in the editor's property panel for world-space labels and is saved with the map.

-- Looks like font size 12, but razor sharp:
set_label({
    parent_name = name, name = "nick", text = nickname,
    font_size = 48, scale = 0.25,
    size = Vector2(512, 96), position = Vector2(-64, -24),
    horizontal_alignment = 1, outline_size = 16
})

Rotation

Every placed element — images, labels, buttons, progress bars, polygons and script entities — accepts a rotation config key in radians. The same value is editable in the editor's property panel as a Rotation field in degrees, works in both the Map tab (world space) and the View tab (HUD), is saved with the map/view (JSON key r) and is covered by undo/redo (Ctrl+Z / Ctrl+Y).

Images, labels, buttons and progress bars rotate around their own centre; polygons and script entities rotate around their origin (the point you see as their position). Rotation set from Lua is local-only and is never synced by itself — call it on every peer, or let DYNAMIC entities sync their own rotation.

-- A label tilted 15 degrees
set_label({ name = "_title", text = "SALE!", rotation = math.rad(15) })

Input Display Names

Use @key_N@ or @stick_N@ in text to show context-aware button prompts:

-- Shows keyboard key or gamepad button automatically
set_label({
    text = "Press @key_7@ to interact\n@stick_1@ to move"
})

set_button(config)

Create or update a clickable button. When the button is pressed it calls run_function(entity_name, function_name, parameters). Buttons can also be placed visually from the editor (Map tab and View tab) where the entity name, function name and parameters are configured in the property panel.

-- A UI button that runs "buy_item" on the shop entity when clicked
set_button({
    name = "_buy_button",
    text = "Buy Potion",
    position = Vector2(20, 60),
    size = Vector2(160, 40),
    font_size = 18,
    entity_name = "-shop",
    function_name = "buy_item",
    parameters = {"health_potion", 3}
})

4.6 Audio System

set_audio(config)

Play audio with various options.

-- Play 2D positional sound
set_audio({
    stream_path = "explosion",  -- loads explosion.ogg
    position = explosion_pos,
    is_2d = true,
    volume = 0,  -- in decibels (-80 to 24)
    pitch_scale = 1.0,
    random_pitch = 0.2,  -- randomize pitch by ยฑ20%
    max_distance = 500
})

-- Play global sound
set_audio({
    stream_path = "background_music",
    is_loop = true,
    volume = -10,
    bus = "Music"
})

set_audio_volume(parent_name, entity_name, volume_db)

Updates the volume of an audio player that is already playing, without restarting it. set_audio always restarts playback from the beginning - even when it reuses an existing player by name - which is fine for a one-shot sound effect but makes it unusable for smoothly fading a continuous looping track (every call would snap it back to the start). Use set_audio_volume instead once the player already exists, calling it repeatedly (e.g. from a timer) to ramp the volume up or down over time - for example, a day/night ambience crossfade.

-- Start a looping ambient track, silent at first
set_audio({
    name = "amb_day", parent_name = "-gm",
    stream_path = "ambient/morning_nature",
    is_loop = true, volume = -60, bus = "Ambient"
})

-- ...then, on a timer, ramp it up toward its real volume
set_audio_volume("-gm", "amb_day", -10)

4.7 Paintable Canvases

The paint system turns a sprite created with set_image into an editable 2D canvas that players can draw on with a brush, eraser and paint bucket, with full undo/redo. It is server-authoritative: the host owns the pixels and the undo/redo history, decides which players (by Steam ID) may edit each image, and rejects unauthorized edits. Clients send paint intents; the host validates and rebroadcasts them. Players who join late automatically receive the current state of every canvas.

The texture is updated at most once per frame, brush dabs are blitted as a cached round mask, and the bucket uses a scanline flood fill, so painting stays fast and deterministic across all peers.

Making an image paintable

There are two ways to enable painting on an image:

-- Create a sprite, then make it a shared whiteboard everyone can draw on (host)
if IS_HOST then
    set_image({ parent_name = "", name = "whiteboard",
                image_path = "white_512", position = Vector2(0, 0) })

    set_paintable({
        name = "whiteboard",
        sync_mode = "live",     -- "live" | "manual" | "none"
        editor_ids = {},        -- empty = everyone may draw; or {"7656119...", ...}
        brush_size = 8,
        alpha_blend = true,     -- false = overwrite RGBA instead of blending
        tolerance = 0.0,        -- flood-fill colour tolerance (0..1)
        max_undo = 32,
        opaque = false,         -- true = never transparent: eraser/clear paint `background`
        background = Color(1, 1, 1, 1)
    })
end

opaque = true is for canvases with nothing drawn behind them, such as a player's painted skin: the eraser and clear_canvas paint the background colour (default white) instead of leaving a hole, a translucent brush or bucket is mixed into the colour already there, and any see-through pixels of the starting image are flattened onto the background once. A canvas that sits on its own backing image (a whiteboard over a white sprite) can leave it off.

Permissions (anti-cheat)

Only the host's set_paintable call defines who may edit an image. Pass an array of Steam ID strings in editor_ids to restrict editing; leave it empty so everyone can draw. Set editable = false to lock a canvas entirely. The host validates every incoming paint intent against this list, so clients cannot draw on images they are not allowed to edit.

-- Only these two players may draw on this canvas
set_paintable({ name = "team_board", editor_ids = { player_a_id, player_b_id } })

For turn-based games where the active drawer changes constantly, use set_painter instead of rebuilding the whole config each time. It flips the drawing permission for a single canvas and replicates only the tiny permission payload, so it is cheap to call every turn. It is purely a network-level permission โ€” it does not open or close the painting panel, only decides who the host will accept strokes from.

-- Hand the canvas to the current drawer; everyone else is rejected by the host
if IS_HOST then set_painter("board", current_drawer_id) end
-- ...later, lock it between turns:
if IS_HOST then set_painter("board", 0) end

Sync modes

-- Reveal every manual-sync canvas to all players (host only)
if IS_HOST then push_canvas() end          -- "" / no name = all canvases
-- ...or reveal just one:
if IS_HOST then push_canvas("whiteboard") end

Choosing a tool

set_paint_tool sets the local player's brush. Colours can be a Color or a hex string. Set active = false to ignore paint calls while your own UI/menu is open.

set_paint_tool({ tool = "brush",  color = Color(1, 0, 0, 1), brush_size = 12 })
set_paint_tool({ tool = "eraser", brush_size = 24 })
set_paint_tool({ tool = "bucket", color = Color(0.2, 0.4, 1, 1) })

Drawing

Drive strokes from your input loop. World positions come from the in-game mouse (inputs.stick_2). Call paint_begin when the draw button goes down, paint_to while it is held, and paint_end when released. If the active tool is the bucket, paint_begin performs a flood fill instead of starting a stroke.

-- _process receives the local player's inputs each frame. key_12 is LEFT MOUSE
-- (a held boolean) and stick_2 is the world mouse position. The table only reports
-- held state, so track the previous frame to detect press (begin) and release (end).
local was_drawing = false
function _process(delta, inputs)
    local pos = inputs.stick_2          -- world-space mouse position
    if inputs.key_12 then               -- left mouse held
        if not was_drawing then
            paint_begin("whiteboard", pos)  -- first frame held = stroke start
            was_drawing = true
        else
            paint_to("whiteboard", pos)     -- continue the stroke
        end
    elseif was_drawing then
        paint_end("whiteboard")             -- released = stroke end
        was_drawing = false
    end

    -- With the bucket tool selected, paint_begin already fills; or fill directly:
    -- if inputs.key_12 then flood_fill("whiteboard", pos) end
end

Undo, redo and clearing

Undo/redo is host-authoritative and per-image (it undoes the last operation on that canvas, whoever made it). Clients can request it; the host applies and syncs the result to everyone.

paint_undo("whiteboard")
paint_redo("whiteboard")
clear_canvas("whiteboard")   -- wipe to transparent (undoable)
remove_paintable("whiteboard")  -- stop treating the image as a canvas

Reading pixels

local c = get_paint_color("whiteboard", inputs.stick_2)  -- Color, or (0,0,0,0) if outside
local can_draw = is_paintable("whiteboard")
local on_canvas = is_point_on_canvas("whiteboard", inputs.stick_2)  -- true if the point hits the image
local info = get_paint_info("whiteboard")  -- { indexed, palette, max_undo, ... } or {} if not a canvas

Ready-made painting panel

Don't want to wire up tools and draw code yourself? create_painting_panel drops a complete paint UI inside a normal popup, already bound to your image. Opening it is all it takes — mouse drawing works and is synced, and every button is functional out of the box: brush, eraser, eyedropper, bucket, line, hollow circle, hollow square, undo / redo / reset, a 32-colour palette and brush-size / opacity sliders. The panel reads the image's paint settings and adapts: undo/redo are disabled when there is no undo allowance, and the free colour picker is disabled on indexed canvases (which instead show the canvas palette). If the image is not paintable, a warning panel appears and nothing opens.

set_paintable({ name = "whiteboard", max_undo = 32 })  -- the image must be paintable first

create_painting_panel({
    name = "whiteboard",        -- REQUIRED: image to paint
    parent_name = "",           -- owning entity (default "")
    title = "Whiteboard",       -- popup title
    close = true,               -- show the close button
    offset_ratio = Vector2(1, 1) -- screen placement (1,1 = centre)
})

The panel closes like any other popup, and the panel name is returned so you can close_panel it yourself.

Two extra options tune the panel: brush_min / brush_max clamp the brush-size slider (e.g. 1 to 32 for a tiny 32×32 sprite), and world_pick (on by default) lets the eyedropper sample colours from the rendered world when you click off the canvas — perfect for matching a disguise to nearby props. You can also read that on-screen colour directly with get_world_color:

create_painting_panel({
    name = "body", parent_name = my_name,
    brush_min = 1, brush_max = 32,   -- slider range for a 32x32 body
    world_pick = true,               -- eyedropper also grabs world colours
})

local col = get_world_color(inputs.stick_2)  -- on-screen colour under the mouse

Note: painting targets map sprites created by set_image. See cenkers_mod_stub.lua for the full parameter list of every paint function.

4.8 Tilemaps & Maps

Maps are built in the in-game editor from one or more tilesets. Each tileset is a source with a stable numeric tileset_id (the first is 0). From Lua you can read and write individual tiles, and switch between maps.

local coords = get_tile(x, y)        -- Vector2 atlas coords, or (-1, -1) if empty
set_tile(x, y, Vector2(3, 1))         -- place tile (3,1) from the first tileset (id 0)
set_tile(x, y, Vector2(3, 1), 2)      -- place from tileset id 2
local world = map_to_local(Vector2(x, y))   -- tile coords -> world position
local tile  = local_to_map(world_position)  -- world position -> tile coords

15-tile dual-grid tilesets

Besides plain tilesets (one tile per cell), a tileset can be a 15-tile dual-grid layer: one 4×4 sheet of transition tiles (mask TL=1 TR=2 BL=4 BR=8; the bottom-left slot, mask 0, is the all-lower tile and may stay empty). The tile is drawn on the corners between cells and chosen from the four cells around each corner, so you only paint cells and every border fits itself. Choose the kind when you press Set as tilemap on an image; everything else is edited in the Tile Maps panel:

From Lua, atlas_coords is ignored for a dual-grid tileset:

set_tile(x, y, Vector2(0, 0), 3)       -- opaque layer 3: its UPPER terrain; transparent: add it
set_dual_tile(x, y, 3, true)           -- opaque layer 3: its LOWER terrain (base terrain for the first)
set_tile(x, y, Vector2(-1, -1), 3)     -- remove layer 3 from the cell
clear_tile(x, y)                       -- plain tile + terrain + every transparent slot
local info = get_dual_tile(x, y)       -- {terrain = id | -2 (base) | -1, overlays = {ids...}}
set_tileset_animation(4, 10)           -- layer 4 now animates at 10 frames per second (local, not saved)
local anim = get_tileset_animation(4)  -- {frames = 6, fps = 10}

Drawing and collision of dual-grid cells are updated in one batch at the end of the frame. Picking variants (e.g. one of several tree sheets per cell) is up to the mod: make each variant its own layer and choose the id from a hash of the cell, as MineBlockLand's worldgen.lua does.

Animated polygon textures

A polygon's texture repeats across its whole shape and can be animated the same way as a 15-tile dual-grid layer: select the polygon, pick its texture, then in the Animation block either Split the image into frames (a horizontal strip of equal frames) or + Add frame (PNG) one image at a time, and set the Frame rate. Every frame must be the size of frame 1. The polygon's Modulate colour multiplies the texture, so a texture that is already blue wants a light modulate (close to white) — a dark blue on top of blue water reads as black. The frames are saved with the polygon (tf = frame list in the same "file.png#k/n" form tilesets use, tfps = frame rate); a still polygon saves exactly as before. All polygons running the same animation stay in step. Hook Up's lakes, sea and cave water use this.

Water reflections

Tick Water reflection on a polygon and it mirrors everything above its top edge onto itself, side-scroller style: players, props, the sky, bent by smooth ripples that grow and blur with depth and a bright line at the surface. The reflection is tinted by the water itself — the polygon's colour, its modulate and the average colour of its texture — so a green cave pool and a deep blue sea reflect the same scene differently, and the texture's own animation stays visible on top. Reflection strength (0–1) sets how much of it shows. The top edge may be sloped or uneven; the mirror follows it. Saved as wr / wrs; polygons without it save exactly as before. Players can turn every reflection off for themselves in Settings → General → Water reflections. Everything is reflected whatever its z, and anything drawn over the water (a hook hanging in it, a swimmer, a foreground prop) is left exactly as it is — only pixels where the water itself shows are changed. The water also darkens with depth, shows faint light shafts, a moving bright line at the surface and twinkling sun glints where something bright is reflected. Hook Up's waters use this.

Erasing tiles

Pass Vector2(-1, -1) as the atlas coords to erase a cell. On a dual-grid layer the neighbours re-fit around the hole by themselves, so you can carve an opening (a doorway, a collapsing wall) at runtime and it still looks right.

set_tile(x, y, Vector2(-1, -1))      -- erase the plain tile of the cell

Minimap (set_minimap / get_minimap)

The engine can render a minimap of the tilemap for any mod — nothing about it is game-specific. It is host-authoritative and off by default: the host must call set_minimap(true) before get_minimap() returns anything. Only the permission flag travels over the network; the map image never does. Every peer builds its own minimap locally from the tiles loaded on its machine, so on procedurally streamed maps it naturally acts as a fog of war.

get_minimap() returns a texture key string (or "" when not allowed) that you pass to set_image as the image_path — the same pattern as Steam avatar ids. The texture keeps updating live while it is on screen: newly loaded chunks and tile edits appear automatically.

Colours are picked deterministically: each (tileset, tile) pair uses the average colour of its texture region, tiles that have collision are drawn darker, and a dual-grid cell takes the full-tile colour of its topmost layer.

-- Host (once, e.g. at boot):
set_minimap(true)

-- Any peer, e.g. when the Map key is pressed (view has a hidden "_map" image):
local map_id = get_minimap()
if map_id ~= "" then
    set_image({ name = "_map", image_path = map_id, visible = true })
end
-- ...and set_image({ name = "_map", visible = false }) to hide it again.

Tracking things on the map. set_minimap_target pins an icon (and optional label) to either a moving entity (entity_name, re-resolved every frame) or a fixed spot (world_position, e.g. the world spawn point) and lets the engine keep it positioned — no per-frame Lua. Targets are local (not networked), so register one per peer — the player entity script is a natural place for a "you are here" dot since it runs on every peer for every player:

-- In the player entity (runs on every peer for every player): your dot is green.
set_minimap_target({
    name = "mm_" .. name, entity_name = name,
    text = nickname, icon_size = Vector2(7, 7),
    color = IS_LOCAL and Color(0.4, 0.8, 0.3, 1) or Color(1, 1, 1, 1),
})
-- delete_minimap_target("mm_" .. name) removes it.

-- A static marker, e.g. the world spawn point (call once, anywhere):
set_minimap_target({ name = "spawn", world_position = map_to_local(Vector2(0, 0)),
    text = "Spawn", icon_size = Vector2(8, 8), color = Color(1, 1, 1, 1) })

This alone is enough to drive the ready-made panel below or your own render loop off get_minimap_target_position(name). If you draw your own minimap HUD from a raw set_image element instead, add image_name (that element's name, must use STRETCH_SCALE) and the engine auto-draws the marker as a child of it too — so it pans/zooms along with your element.

Ready-made panel. create_minimap_panel is the minimap twin of create_painting_panel: it opens a popup with the live map, zoom in/out, a lock-on-target toggle that keeps a tracked entity centred, and < / > arrows to cycle between your set_minimap_target markers — all with no UI code. Use it, or build your own HUD from the calls above.

create_minimap_panel({ title = "Island Map", lock_target = LOCAL_STEAM_ID })

Raycasting the world

raycast shoots a 2D ray through the physics world (walls, entity bodies, areas) and returns the first hit. For anti-cheat, do this on the host from the entity's real position — clients just send where they aimed. Use collision_mask to pick which layers count and exclude so the shooter never hits itself.

-- Host validates a shot: 4 tiles (128px) toward the aim point, hitting walls
-- (layer 1) and players (layer 2), ignoring the shooter's own body.
local hit = raycast({
    from = get_value("", shooter_id, "position"),
    direction = aim - get_value("", shooter_id, "position"),
    length = 128,
    collision_mask = { 1, 2 },
    exclude = { shooter_id },
})
if hit.hit and players[hit.collider] then
    -- hit.collider is the entity name that was struck; hit.position is where.
end

4.9 Card System (tabletop decks & hands)

The engine ships a host-authoritative tabletop card runtime (think Tabletop Simulator, but cheat-proof): the deck order exists only on the host, and a card's identity is only ever sent to the peers that are allowed to know it. Everyone else โ€” players and spectators alike โ€” sees card backs, hand counts and movement animations. The bundled Crazy Eights and Operation: Detonate mods are complete working examples.

1. Define the cards (every peer)

Card definitions (what cards look like + their keywords) load identically on every peer from your mod's own files or code โ€” usually in world.lua:

-- A) A set designed in the Online Asset Editor's CARD EDITOR and exported as JSON:
load_cards_from_json("cards/my_set.cards.json")

-- B) Procedurally, straight from a Lua table (same structure as the JSON):
load_cards_from_data({
    kind = "cards", set_id = "demo", card_w = 750, card_h = 1050,
    corner_radius = 0.08, safe_margin = 0.055,
    back = { type = "color", color = "(0.13, 0.13, 0.18, 1)" },
    cards = {
        { id = "red_7", keywords = { power = 7 },
          bg = { type = "color", color = "(0.72, 0.11, 0.11, 1)" },
          corner = { text = "7", spots = { "tl", "br" }, flip_opposite = true, size = 0.16 },
          layout = { type = "vbox", children = {
              { type = "text", text = "7", font_size = 0, keyword = "value" }, -- 0 = auto-fit
          } } },
    },
}, "demo")

-- C) From a pre-rendered PNG sprite sheet:
load_cards_from_png({ set_id = "png", front_sheet = "sheet.png", cols = 5, rows = 2,
    back_image = "back.png", ids = { "a", "b", "c" } })

-- Keywords make rules easy:
local power = get_card_keyword("red_7", "power")   -- 7

Faces are rendered locally by the same renderer the editor preview uses; you can also show any face with a normal image: set_image({ image_path = "card:red_7:front" }).

Card text is localized like everything else

Never write the words on a card in Lua. Give a text cell a loc_key (and put the same key in the cell's text as a {keyword}), then translate that keyword in your mod's own general/language/<mod>_<code>.json files โ€” the same files that translate your labels, panels and chat lines. Faces render live, so every peer sees the deck in their language and the cards re-render by themselves when someone changes it:

-- world.lua: keywords only, no prose
{ type = "text", text = "{bomb_title}", loc_key = "bomb_title", keyword = "title" }

-- general/language/mymod_tr.json
-- "keys": { "{bomb_title}": "Saatli Bomba" }

A card's name can be a keyword too (name = "{bomb_title}"), so the panels and chat lines that print it are translated as well. Resolution order for a loc_key is: your mod's language files first, then the set's own optional localization table (what the Card Editor exports, for sets used outside a mod), then the cell's plain text as the last fallback. The bundled Operation: Detonate mod is written exactly this way โ€” its world.lua holds no card text at all.

2. Shared state (HOST only mutates)

-- host:
card_create_deck({ name = "draw", position = Vector2(-75, 0),
    cards = { "red_7", "red_7", "blue_2" },   -- duplicates fine; index 1 = top
    size = Vector2(96, 134),
    visibility = "owner" })  -- "owner" | "all" | "none": who learns a drawn card
card_shuffle("draw")          -- optional seed: card_shuffle("draw", 12345)
local uid = card_draw("draw", steam_id)        -- deal to a hand
card_play(uid, Vector2(75, 0), true)           -- face-up play reveals to everyone
card_peek("draw", 3, steam_id)                 -- private top-3 (See-the-Future)
local ids = card_peek_host("draw", 3)          -- same, but returned directly (for bot AI - no peer to callback)
card_return_to_deck(uid, "draw", -1)           -- back into the deck (random spot)
card_transfer("", victim_id, thief_id)         -- random steal between hands

Clients never call these directly โ€” they send intents (run_network_function(name, "draw_HOST", {})), the host validates the turn/rules (on the host card_get_hand() always contains real identities) and then calls the card_* functions.

3. React (listener callbacks)

card_set_listener("-my_manager")   -- which entity receives _on_card_* callbacks
card_set_player_anchor(steam_id, seat_pos)  -- where that player's cards fly from/to
card_set_hand_ui({ height = 150, separation = -34 })  -- the local bottom hand bar
card_set_drop_zone(table_center, 200)  -- drag a hand card here to play it (else it snaps back)

function _on_deck_clicked(deck_name) end            -- local input
function _on_hand_card_clicked(uid, card_id) end    -- local input: tapped your own hand
function _on_hand_card_dropped(uid, card_id) end     -- local input: DRAGGED a hand card into the drop zone
function _on_card_drawn(owner, deck_name, uid) end  -- every peer
function _on_card_played(owner, uid, card_id) end   -- card_id "" when hidden from you
function _on_card_peek(deck_name, ids) end          -- only on the peeking peer

Hand cards support both a tap (_on_hand_card_clicked) and a drag-and-drop (_on_hand_card_dropped, only fires when the card is released inside the card_set_drop_zone radius โ€” dropped anywhere else, it just snaps back to the hand). Mods usually route both callbacks to the same "try to play this card" function.

For the full function list (queries like card_hand_counts(), card_uid_info(), flips, moves, discards) see cenkers_mod_stub.lua โ€” every function is documented there.

Tabletop camera

set_camera_rotation(radians) rotates the view; seat players around a circle and rotate each player's camera so their own seat is at the bottom of their screen. Screen-space UI (the hand bar, panels) is unaffected. Both card mods do exactly this.

Rotating the camera tilts everything drawn in world space too โ€” cards, seat avatars, name labels โ€” which reads upside-down/sideways to the seated player unless you counter-rotate them. card_set_world_rotation(radians) does this for every card/deck/hand-fan node the card system owns (pass the same angle you gave set_camera_rotation); for your own set_image/set_label elements (seat avatars, name tags), pass the same angle as their rotation config key. All of this is purely local presentation โ€” only positions are ever networked, so every peer computes and applies its own counter-rotation independently.

Drop shadow

Every card set carries a shadow config (on by default โ€” { enabled, color, dx, dy, grow }, all editable in the Card Editor's Set panel) describing a flat, hard-edged silhouette behind the card โ€” there is no softness/blur control, on purpose: a card shadow is cheap exactly because it is a solid shape, not a blurred one. How it gets applied depends on how the set was loaded:

load_cards_from_png also supports per-language sheets by file name (mirroring the image_localizer tool's convention): given front_sheet = "cards.png", it looks for a sibling cards_<lang>.png matching the engine's current locale (e.g. cards_tr.png) and uses it when present, falling back to the base file name otherwise. back_image is resolved the same way.

Outline

Every card set also carries an outline config โ€” off by default โ€” { enabled, color, width }, editable next to Shadow in the Card Editor's Set panel. A colored ring drawn right at the card's own edge, following its corner rounding, on top of the background/content/corner-indices so it is never hidden. Unlike the shadow, this is baked straight into the face (front and back) for every load path โ€” it's an ordinary render layer, not a separate presentation node, so there is nothing extra to configure at runtime.

The Card Editor in the Online Asset Editor

The Online Asset Editor (main menu) bundles the Image, Music, Visual Novel and Card editors as tabs in one shared session โ€” switch tools with the buttons just above the yellow Invite Friend button (each shows who is working in that tab), no need to leave the lobby and re-host. The Card Editor is its own tab, laid out left to right in the order you work: the card list (every card in print order, click to select), the preview (click a region on the card to edit exactly that part), the properties column (only the selected set/card/cell) and Text & Languages. The whole session designs one card set together (fully synced, autosaved, and saveable as its own project file):

4.10 Visual Novel & Branching Stories

The engine ships a scenario runtime for stories authored in the Online Asset Editor's Visual Novel tab (or built by hand). It is not a full VN engine โ€” it is the story graph: characters, dialog nodes, choices (with tags, conditions and secret options) and variables. Everything visual is your mod's job: node and choice bg, sound and a character mood image are plain path strings you feed to set_image / set_audio, so fades, character placement, effects, inventories and puzzles all stay ordinary Lua you write yourself. The bundled School Days mod is a complete working example (a vote-driven, multi-ending school story).

Authoring in the editor

The Visual Novel tab is a mindmap: dialog nodes float as draggable boxes, wires show the flow (gray = the linear next link, colored = choices), and the whole session edits the same story live. Per node you set the speaker + mood, the dialog text, a background and sound, tags, and variable operations that run when the node is entered. Choices carry text, tags, a target node, conditions (all must hold or the choice is disabled โ€” or hidden entirely if marked secret) and their own variable operations. A background or mood image can be linked to a canvas from the Image tab for a live preview and an optional PNG next to the exported JSON โ€” but the story JSON only ever stores the path string. Preview test-plays the story locally using the exact same rules the runtime uses. Export writes the story JSON your mod loads with vn_load.

Deterministic & local by design

Each peer loads the same story file and advances its own copy with explicit calls. The engine never networks story state for you โ€” so a multiplayer story stays host-authoritative the usual way: clients send an intent, the host decides, and every peer runs the same vn_choose() so variables and the current node stay in lockstep. For a voting game that means: clients send their pick with run_network_function(mgr, "vote_HOST", {id = choice_id}); the host tallies, and when the timer ends (or everyone has voted) broadcasts the winner with "apply_choice_ALL"; each peer calls vn_choose(story, winner_id).

-- world.lua (every peer): load the story once
story = vn_load("general/school_days.json")
vn_set_listener("-sd_manager")   -- who gets the _on_vn_* callbacks

-- -sd_manager (every peer): render whatever a node describes, your way
function _on_vn_node(story_id, node)
    set_background_texture(node.bg)                       -- your background
    if node.image ~= "" then
        set_image({ parent_name = "", name = "speaker", image_path = node.image })
    end
    set_label({ name = "_vn_name", text = node.char_name, font_color = node.char_color })
    set_label({ name = "_vn_text", text = node.text })
    if node.sound ~= "" then set_audio({ stream_path = node.sound }) end
    -- Build choice buttons yourself from vn_choices(); disabled ones are up to you
    for _, c in ipairs(vn_choices(story_id)) do
        -- c = { index, id, text, tags, next, enabled, hidden }
    end
end

-- Tag-driven effects live entirely in your Lua:
function _on_vn_choice(story_id, node_id, choice)
    for _, tag in ipairs(choice.tags) do
        if tag == "flirt" then create_particle(...) end     -- your effect
    end
end

Key functions (see the stub for full signatures): vn_load / vn_load_data, vn_start, vn_current, vn_choices (conditions already evaluated: disabled choices come back enabled=false, secret failing ones are omitted), vn_advance (linear next), vn_choose (rejects a choice whose conditions fail), vn_goto, vn_is_end, vn_get_var / vn_set_var / vn_get_vars, and vn_node_info / vn_node_ids for inspecting the graph. Callbacks: _on_vn_node, _on_vn_choice, _on_vn_end.

4.11 Visual Effects (vignette, shadows & hit feedback)

Two screen-wide effects can be driven from Lua. Both take a config dictionary and only touch the keys you pass, so you can animate a single property cheaply. They are local to each peer - broadcast one network message (e.g. a day/night phase change) and let every peer apply the visuals itself.

set_vignette(config)

set_vignette({
    visible = true,
    strength = 1.3,     -- darkness intensity
    radius = 0.6,       -- clear circle size (0..1)
    smoothness = 0.5,   -- edge softness (0..1)
    color = Color(0, 0, 0, 1)
})
local v = get_vignette_settings()  -- { visible, smoothness, strength, color, radius }

flash_vignette(config)

A one-shot colored flash that fades back out on its own. It renders on its own overlay, completely separate from set_vignette, so triggering a flash never reads or overwrites whatever set_vignette is currently showing - the two layer cleanly on top of each other.

-- e.g. a quick colored flash on some event, local player only:
flash_vignette({ color = Color(0.8, 0.05, 0.05, 1), duration = 0.25 })
KeyDefaultMeaning
colorredFlash color (Color, [r,g,b,a], or string)
duration0.25Seconds to fade back to invisible
strength1.6Vignette shader strength
radius0.35Clear circle size (0..1)
smoothness0.35Edge softness (0..1)

set_shadow(config)

The same tile-shadow effect configured per map in the editor's "Shadow Effect Settings", now scriptable. Perfect for a sun that moves across the sky: animate shadow_angle during the day and hide shadows at night.

-- Day/night example (each peer runs this locally on a timer):
if is_night then
    set_shadow({ visible = false })
    set_vignette({ visible = true, strength = 1.3, radius = 0.6 })
else
    local progress = t / DAY_SECONDS                 -- 0 at dawn, 1 at dusk
    set_shadow({ visible = true, shadow_angle = 100 + 160 * progress })
    set_vignette({ visible = false })
end

local s = get_shadow_settings()
-- { visible, shadow_color, shadow_angle, shadow_length, shadow_blur }
Key Meaning
visible Enable/disable the whole shadow pass
shadow_color Shadow colour; the alpha is the darkness
shadow_angle Light direction in degrees (0-360)
shadow_length Cast length in pixels
shadow_blur Blur strength (0-10)

set_shadow_of_image(entity_name, image_name, enabled, y_offset?)

Gives an image a ground shadow that is part of the map's shadow: a blurred clone of the image itself (its alpha), standing on its lowest opaque pixel and laid on the ground in the direction the walls' shadows fall. It is exactly shadow_length long and fades to nothing at the tip, like a wall's shadow, and gets blurrier toward the tip. A tree throws a tree-shaped shadow. Image shadows are merged into the global shadow before its colour is applied, so wherever shadows overlap — two images, or an image and a wall — the alpha stays exactly the same. An image is never darkened by an image shadow (wall shadows still darken it). It follows set_shadow (colour, angle, length, visibility). An image drawn round by the circle shader (Steam avatars) casts a round shadow.

set_image({ parent_name = name, name = "body", image_path = "hero" })
set_shadow_of_image(name, "body", true)            -- standing on the ground
set_shadow_of_image(name, "wings", true, 10)       -- flying 10 px above its shadow
set_shadow_of_image(name, "body", false)           -- remove it

set_shader(config) - sprite shaders

set_shader puts one of the shaders in res://shaders/ on a sprite you created with set_image. Any extra key in the config is passed straight to the shader as a uniform, and uniforms stay on the material, so a later call only has to send the values that changed. Pass an empty shader_name (or leave it out) to remove the shader entirely.

Hit feedback: the "hit_flash" shader

The impact effect every action game needs - the sprite flashes solid white, squashes wider and shorter, and wobbles back upright on an elastic curve. All three are driven by one uniform, hit: set it to 1.0 on the frame of impact and fade it to 0.0 over about a quarter of a second. At hit = 0.0 the shader does nothing at all, so it is free while nobody is being hurt. Only RGB is flashed, so transparent pixels stay transparent.

A sprite can only carry one material, so the "circle" shader (the outline used by most character sprites) carries the identical uniforms. Use "circle" for anything already outlined and "hit_flash" for a plain sprite.

-- On the frame of impact (run this on EVERY peer - piggy-back it on the
-- damage broadcast your mod already sends, it needs no message of its own):
set_shader({ parent_name = name, image_name = "body", shader_name = "hit_flash",
    hit = 1.0, hit_dir = math.cos(hit_angle) })

-- Then fade it out. Because the uniforms persist, each later frame is one float:
set_shader({ parent_name = name, image_name = "body", shader_name = "hit_flash",
    hit = remaining / 0.26 })

-- When it reaches 0, take the material off again (or, for "circle", re-send
-- the shader with hit = 0 so the outline survives):
set_shader({ parent_name = name, image_name = "body", shader_name = "" })
UniformDefaultMeaning
hit0.0Effect strength 0..1. 1 = the frame of impact
hit_dir1.0Sign of the wobble. Pass cos(hit angle) so the sprite tips away from the blow
hit_colorwhiteThe flash colour
hit_squash0.35Peak horizontal stretch; the vertical squash is 1/x, so the silhouette keeps its area
hit_spin0.3Peak rotation in radians
hit_wobbles2.5Oscillations over the life of the effect
hit_flash_start / hit_flash_full0.6 / 0.75The flash is a hold, not a fade: solid colour while hit is above hit_flash_full, gone below hit_flash_start. A flash that fades from the first frame reads as a tint, not an impact

Drive every live effect from one singleton, not from each victim. Campfire Survivors and MineBlockLand both ship a hit_fx.lua singleton whose _process ticks only the handful of sprites that are flashing right now; a _process in every monster script would cost a Lua call per monster per frame just to find out there is nothing to do. Guard the per-frame call with entity_exists(image_name, entity_name) - the killing blow destroys its target while the flash is still playing, and every other lookup would log an error for each of those frames.

CRT and screen noise

Two more full-screen looks, drawn behind the HUD like the vignette and, like it, set per map in the editor's map settings (CRT Effect Settings, Screen Noise Settings) and changeable at runtime. Both are local, so each player can see something different - e.g. a CRT that gets stronger as a monster gets closer.

set_crt({ visible = true, intensity = 0.3 })            -- scanlines, colour fringing, flicker
set_screen_noise({ visible = true, intensity = 0.1 })  -- film grain
local crt = get_crt_settings()
set_crt keyDefaultMeaning
visiblefalseOn / off
intensity0.350..1, scales everything at once
scanline_size3Pixels per scanline pair (base-resolution pixels, the same at any window size)
scanline_strength0.35How dark the scanlines get
aberration1.5Colour fringing at the screen edge (pixels)
flicker0.04Brightness flicker
set_screen_noise keyDefaultMeaning
visiblefalseOn / off
intensity0.120..1 opacity
grain_size2Grain size (base-resolution pixels)
speed24New grain patterns per second
colorwhiteGrain colour

4.12 Particles

GPU particle bursts - sparks, chips, smoke, splashes. You define a reusable template once with create_particle, then fire as many instances of it as you like with start_particle. Templates are cached by particle_id, so calling create_particle again with the same id simply replaces the old one.

Particles are local: nothing is sent over the network. If every peer should see the same burst, broadcast one small message and have each peer call start_particle itself.

create_particle(config)

-- A ring that grows and fades, e.g. a splash under a player wading through water:
create_particle({
    particle_id = "water_ring",
    texture_path = "splash",       -- from your mod's general/images/ (.png optional)
    lifetime = 0.45,
    amount = 1,
    one_shot = true,
    explosiveness = 1.0,           -- 1.0 = emit everything at once
    initial_velocity_min = 0,
    initial_velocity_max = 0,
    scale_amount_min = 0.9,        -- PEAK size (scale_curve multiplies this)
    scale_amount_max = 1.1,
    scale_curve = { 0.35, 1.0 },   -- grow over the lifetime
    alpha_curve = { 1.0, 0.0 },    -- fade out over the lifetime
    color = Color(1, 1, 1, 0.8),
    z_index = 1
})
KeyDefaultMeaning
particle_id-Required. Unique template id
texture_path""Image in your mod's general/images/; .png added if omitted
lifetime1.0Seconds each particle lives
amount50Particle count
one_shottrueEmit once (instance frees itself when done) or loop forever
explosiveness0.00 = spread emission over the lifetime, 1 = all at once
randomness0.0Emission timing randomness (0..1)
direction / spread-Emission direction {x=,y=} and cone angle in degrees
initial_velocity_min/max0 / 1Launch speed range
angular_velocity_min/max0 / 0Spin speed range
gravity-Gravity vector {x=,y=}
scale_amount_min/max1 / 1Constant size range
scale_curve-Size over the lifetime, evenly sampled, e.g. {0.35, 1.0} grows. Multiplies scale_amount_min/max, so set those to the peak size. Needs 2+ numbers; pass more for a custom shape
alpha_curve-Opacity over the lifetime, evenly sampled, e.g. {1.0, 0.0} fades out. Needs 2+ numbers
angle_min/max0 / 0Starting rotation range in degrees
colorwhiteParticle tint
color_randomfalseRainbow gradient - confetti
hue_variation_min/max0 / 0Per-particle hue jitter
local_coordsfalsefalse = particles stay in world space once emitted; true = they follow the parent
z_index10Draw order, clamped to [-999, 999]. The default sits above ground tiles

start_particle(config)

Spawns one instance of a template and returns its instance name. A one_shot instance frees itself when it finishes, so you never have to clean it up.

-- Free-floating in the world:
start_particle({ particle_id = "water_ring", position = Vector2(x, y) })

-- Or attached to an entity. With local_coords = false (the default) the particles
-- still stay where they were emitted, but the z_index is now relative to that
-- entity - handy for drawing the effect underneath a character's sprite.
start_particle({ particle_id = "water_ring", parent_name = name,
    position = Vector2(0, 6) })   -- position is relative to the parent
KeyDefaultMeaning
particle_id-Required. A template made with create_particle
parent_name""Entity to attach to; empty = free-floating in the world
position(0,0)World position, or offset from the parent
rotation0.0Emitter rotation in radians
instance_nameautoName to pass to stop_particle / get_particle_data later

The rest: stop_particle(instance_name) kills a running instance (needed for looping ones), get_particle_data(instance_name) reports its state, cleanup_entity_particles(entity_name) clears everything attached to an entity (already called for you when an entity is destroyed), and get_active_particle_count() / get_cached_particle_count() help when you are chasing a leak.

4.13 Localization

Your mod can ship in as many languages as you like. Put one JSON per language in general/language/ and write keywords instead of text. The game swaps them for the player's language as it draws, so a mod that never calls a localization function still gets translated.

The language file

-- general/language/mymod_en.json
{
  "meta": { "code": "en", "name": "English", "native_name": "English", "flag": "gb" },
  "keys": {
    "{score}": "Score",
    "{you_win}": "You win!",
    "{wait_seconds}": "WAIT %s SECONDS"
  }
}

-- general/language/mymod_tr.json
{
  "meta": { "code": "tr", "name": "Turkish", "native_name": "Tรผrkรงe", "flag": "tr" },
  "keys": {
    "{score}": "Skor",
    "{you_win}": "Kazandฤฑn!",
    "{wait_seconds}": "%s SANฤฐYE BEKLEYฤฐN"
  }
}

meta.flag is an ISO country code and picks the flag icon shown in the language menu. Adding a language is only adding a file โ€” no code changes, no registration.

Name the file after your mod (mymod_en.json, not en.json): the language code is read from the part after the last _. When a lobby merges your mod with addons every folder is copied into one place, so a bare en.json can be replaced by another mod's and all of your labels would show up as raw {keyword}.

Using a keyword

set_label({ name = "_score", text = "{score}: " .. points })
add_to_chat("{you_win}")
create_panel({ text = "{you_win}" })

Anything with no keyword in it is shown exactly as written, so you can mix freely.

Rules that save you debugging time

-- wrong: the suffix cannot agree with whatever word lands there
set_label({ name = "_t", text = "{buy} " .. item_name .. "'s" })
-- right: the grammar lives in the translated string you control
set_label({ name = "_t", text = string.format(translate("{buy_item}"), item_name) })

Functions

FunctionReturnsUse it for
get_current_language()stringThe player's language code, e.g. "tr"
get_languages()tableEvery installed language code
get_language_info(code)table{ code, name, native_name, flag }
translate(text, lang?)stringThe resolved value โ€” comparisons, string.format
translate_all(text)tableEvery language at once: { en = "fox", tr = "tilki" }

Word games: accepting an answer in any language

Keep the word list as keywords. Each player sees the word in their own language, and the host accepts the answer whichever language it was typed in โ€” so both "fox" and "tilki" win.

local word_pool = { "{w_fox}", "{w_apple}", "{w_house}" }

-- every peer shows the secret word in its own language
set_label({ name = "_word", text = secret_key })

-- HOST: the guess is correct in ANY installed language
function check_guess(guess, secret_key)
    for _, word in pairs(translate_all(secret_key)) do
        if normalize(guess) == normalize(word) then return true end
    end
    return false
end

4.14 Pathfinding (AStar)

Monsters that walk around walls instead of into them. The engine builds a grid of half tiles from your map: plain tiles with collision, the collision quarters of 15-tile dual-grid layers and polygon walls are blocked, one-way tiles are not. Changing tiles at runtime (set_tile, opening a door...) updates the grid by itself, and nothing is built until you first ask for a path, so maps that never use it pay nothing.

navigate_to(entity_name, target, config)

The go_to_target of pathfinding: the engine steers the entity every physics frame at its speed (pixels per second) and calls _on_navigation_finished(reached) on it when it arrives (true) or gives up (false: no path, or stuck). Give an entity name as the target and it is followed, the path being recomputed while it moves; give a Vector2 for a fixed spot; "" stops it without a callback. Players move by input, so they cannot be navigated. For a DYNAMIC entity (network_mode = 2) call it on the host - the movement is synced like any other.

-- monster.lua
network_mode = 2
speed = 110
lock_rotation = true

function patrol()
    navigate_to(name, room_centers[math.random(#room_centers)])
end

function chase(steam_id)
    navigate_to(name, steam_id, { stop_distance = 12 })   -- follows the player around corners
end

function _on_navigation_finished(reached)
    if IS_HOST then patrol() end
end
KeyDefaultMeaning
stop_distance8Arrive when this close to the target (pixels)
speedthe entity's speedPixels per second
rotatefalseTurn the entity to face where it walks
radius6Body radius used when straightening the path

Other functions

FunctionReturns
find_path(from, to)Waypoints {Vector2, ...}, or an empty table when there is no path. A target inside a wall is moved to the nearest walkable spot.
is_point_walkable(world_pos)true if pathfinding may walk there
has_line_of_sight(from, to)true if no wall that casts a shadow lies in between (furniture without a shadow does not block) - the same rule as the fog of war, ideal for "can the monster see the player?"
set_pathfinding(config) / get_pathfinding()Change / read diagonal, wall_weight, clearance at runtime

Settings in the map editor

Tile Maps → map settings → Pathfinding (AStar) saves them into the map's info.json:

Keep a navigated entity's collision circle at most a quarter tile in radius (8 px on 32 px tiles) with clearance 0, or raise the clearance - otherwise it brushes against corners.

4.15 Fog of War

Hide what a player cannot see. Fog of war is local: every peer runs its own and nothing travels over the network, so turn it on from the local player's script. Never-seen ground is black, ground seen before is dimmed, and everything within radius tiles the origin has a line of sight to is shown normally. Sight is blocked by whatever casts a shadow - the shadow setting of a plain tile, a dual-grid layer's shadow quarters, a polygon's shadow type - so walls block it and desks do not.

-- user.lua
if IS_LOCAL then
    set_fog_of_war(true, name, { radius = 8, hide_tag = "fog_hide" })
end
add_tag(name, "fog_hide")   -- other peers hide this player while they cannot see it
KeyDefaultMeaning
radius8Sight radius in tiles
explored_colorColor(0, 0, 0, 0.65)Over ground seen before but not visible now
unexplored_colorColor(0, 0, 0, 1)Over ground never seen
softness1Width of the soft edge of the sight circle, in tiles
hide_tag""Entities with this tag disappear while the origin cannot see them - only their drawing, their visible flag is left alone
resetfalsetrue forgets everything explored so far (a new round)

reveal_fog(world_pos, radius_tiles, seconds) uncovers a circle for a while, walls or not - a noise the player heard, a flare. Hidden-tag entities inside it show up too.

set_fog_of_war(false) turns it off; loading a map turns it off too. get_fog_state(world_pos) returns 0 (never seen), 1 (seen before) or 2 (visible now) - always 2 while the fog is off.

4.16 Roles & Dedicated Servers

Hosting through a custom master server and dedicated servers are experimental - see 8. Dedicated & Master Servers.

A game can be hosted three ways, and a mod should work in all of them without knowing which:

Every player has a role: host > owner > moderator > player. The host is the lobby owner (or the dedicated server itself), owners are listed in a dedicated server's server.json, and moderators are appointed in game.

FunctionReturns
is_admin(id)true for the host and for owners. On a listen server this is exactly id == HOST_STEAM_ID.
get_role(id)"host", "owner", "moderator" or "player"
can_moderate(actor, target)true when the actor is a moderator or above and strictly outranks the target
add_moderator(id) / remove_moderator(id)HOST ONLY; false when nothing changed
get_moderators()The moderators' ids
kick_user(id, reason, actor) / ban_user(id, seconds, reason, actor)With actor given, the engine refuses unless can_moderate(actor, id) - pass the requesting player's sender_id when you relay a request

Rules that make a mod work on a dedicated server

local function admin_online()
    for _, id in ipairs(get_entity_names_by_tag("user")) do
        if is_admin(id) then return true end
    end
    return false
end

function start_HOST(sender_id)
    if not IS_HOST then return end
    if is_admin(sender_id) then begin_round() return end
    if admin_online() then return end          -- the admin decides
    votes[sender_id] = true
    if count(votes) > #get_entity_names_by_tag("user") / 2 then begin_round() end
end

Players who joined without Steam have a generated avatar (or one they chose): it arrives through the same _on_loaded_avatar callback and the same set_image({image_path = id}) as a Steam avatar.

4.17 Player Ids: Steam ID & Local User Id

Every player has exactly one id, and every id-taking function (sender_id, LOCAL_STEAM_ID, is_admin(id), entity names of users...) works the same with both kinds:

KindWhoLooks like
Steam IDa player signed in through Steamalways 17 digits, starts with 7656119
Local user ida player without Steam (LAN, custom master, dedicated server), or an extra game window of a player in a room that allows several windows always 15 digits

What you can do with an id

Everything below takes either kind of id, the same way. A mod never needs to check which kind it got.

UseHow
Who sent a network callthe sender_id argument of a _HOST/_ALL/_CLIENT function
Send to one player onlyrun_network_function(name, "f_CLIENT", params, id)
The player's entitya user entity is named by its id: get_entity(id), entity_exists(id), set_fog_of_war(true, id, ...)
Join / leave / kick / ban callbacks_on_user_connected(id, nickname), _on_user_initialized, _on_user_disconnected, _on_user_kicked, _on_user_banned
Roles and moderationis_admin(id), get_role(id), kick_user(id, ...), ban_user(id, ...); ids in server.json owners
Who may draw on a canvasset_painter(image_name, id), editor_ids
Cardscard_draw(deck, id), card_get_hand(id), card_transfer(uid, from_id, to_id)
Saved data per playeruse the id string in the file name or table key

Avatars

Every player has an avatar:

The avatar arrives some time after the player joins. When it is ready, _on_loaded_avatar(id) is called on the player's entity. From then on, pass the id as an image path to show the avatar. Both 17-digit and 15-digit ids work there:

local avatar_ready = false

function _on_loaded_avatar(id)
    avatar_ready = true
    set_image({ parent_name = name, name = "avatar", image_path = id, scale = Vector2(32, 32) })
    set_shader({ parent_name = name, image_name = "avatar", shader_name = "circle" })
end

An id is only read as an avatar while that player is connected. Before _on_loaded_avatar, or for a player who has left, the same text is looked up as an ordinary file in general/images/, so pass "" until the avatar is ready.

Steam only

4.18 Player Cursors

Shows every other player's mouse cursor in the world, with their name under it: who is pointing at which card, where a team-mate is aiming. One call turns it on; the engine sends, relays, smooths and draws the cursors itself.

set_cursor(enabled, text, color, icon, steam_id)
ParameterMeaning
enabledtrue shows the cursors, false hides them.
textLabel under the cursor. nil = the player's nickname, "" = no label, anything else is shown as it is; {keyword} tokens are translated on each player's own screen.
colorTint of the icon and label. nil = an automatic colour, different for each player.
iconA PNG in general/images/ (".png" optional), drawn 32×32 and centred on the mouse. nil = the game's own hand cursor, pointing with its fingertip.
steam_idOptional. Applies the call to that one player only; its nil fields fall back to the setting for everyone. nil = everyone.
-- world.lua (runs on every player, so this one line is all most mods need)
set_cursor(true)

-- user.lua: give this player's cursor their own colour
set_cursor(true, nil, outline_color, nil, name)

-- a team game: hide the other team's cursors on this screen
set_cursor(false, nil, nil, nil, enemy_id)

5. Practical Examples

Example 1: Creating a Projectile (from Hook Up)

-- hook_projectile.lua
linear_damp = 0
gravity_scale = 0.5
lock_rotation = true
network_mode = 2  -- DYNAMIC: synced continuously

-- Owner data (set when spawned)
-- owner_name = "steam_id_of_player"

add_tag(name, "hook")

-- Create visuals and collision
function create_hook_components()
    set_image({
        parent_name = name,
        name = "hook_image",
        image_path = "hook",
        modulate = modulate or Color(0.7, 0.7, 0.9, 1),
        visible = false
    })

    set_collision({
        parent_name = name,
        name = "hook_collision",
        shape = "circle",
        size = 10,
        collision_layer = {3},
        collision_mask = {1, 4}  -- Walls and water
    })
end

create_hook_components()

function activate_hook()
    set_image({
        parent_name = name,
        name = "hook_image",
        visible = true
    })
    set_collision({
        parent_name = name,
        name = "hook_collision",
        disabled = false
    })
end

function deactivate_hook()
    set_value("", name, "linear_velocity", Vector2(0, 0))
    set_image({
        parent_name = name,
        name = "hook_image",
        visible = false
    })
    set_collision({
        parent_name = name,
        name = "hook_collision",
        disabled = true
    })
end

-- Handle collision
function on_body_body_entered(collision_info)
    if not IS_HOST then return end

    local owner_state = get_value("", owner_name, "hook_state")
    if owner_state ~= "FIRING" then return end

    local other_entity = collision_info.body_name
    if has_tag(other_entity, "user") then return end

    -- Attach hook
    freeze_entity(name, true)
    run_network_function(owner_name, "set_hook_state_ALL", {"ATTACHED"})
end

-- Handle area collision (water detection)
function on_body_area_entered(area_name)
    if not IS_HOST then return end

    local owner_state = get_value("", owner_name, "hook_state")
    if owner_state ~= "FIRING" then return end

    if has_tag(area_name, "sea") or has_tag(area_name, "lake") then
        run_network_function(owner_name, "set_hook_state_ALL", {"SEARCHING"})

        -- Determine water type for fishing
        local water_source = has_tag(area_name, "sea") and "sea" or "lake"
        run_function("-fishing_game", "start_searching_for_player",
                     {owner_name, water_source})
    end
end

Example 2: Stat System (from Campfire Survivors)

-- user.lua excerpt
-- Define default stats as global variables (each entity has its own globals)
movement_speed = 40
max_health = 100
current_health = 100
armor = 0
damage = 30
attack_speed = 1.0
projectile_count = 1

-- Note: Each entity has its own separate global scope
-- There is no shared _G table between entities
set_value("", name, "speed", movement_speed)

-- Called by upgrade system when stats change
function update_stats(stats)
    -- Update global variables in this entity's scope
    movement_speed = stats.movement_speed
    max_health = stats.max_health
    current_health = stats.current_health
    armor = stats.armor
    damage = stats.damage
    attack_speed = stats.attack_speed
    projectile_count = stats.projectile_count

    -- Update derived values
    set_value("", name, "speed", movement_speed)

    if IS_LOCAL then
        set_progress_bar({
            name = "_health_progress_bar",
            max_value = max_health,
            value = current_health
        })
    end

    -- Restart shooting timer with new attack speed
    if IS_HOST then
        stop_timer("shoot_timer"..name)
        start_timer({
            entity_name = name,
            timer_id = "shoot_timer"..name,
            wait_time = 1.0 / attack_speed,
            function_name = "shoot_at_nearest_monster"
        })
    end
end

-- Shooting function
function shoot_at_nearest_monster()
    if is_dead then return end

    local nearest = get_nearest_entity_by_tag(name, "monster")
    if not nearest or not nearest.name then return end

    for i = 1, projectile_count do
        local angle_offset = 0
        if projectile_count > 1 then
            angle_offset = (i - 1) * (2 * math.pi / projectile_count)
        end

        spawn_entity_host({
            t = "bullet",
            p = position,
            r = nearest.angle + angle_offset,
            steam_id = name,
            damage = damage,
            speed = projectile_speed,
            penetration = projectile_penetration
        })
    end
end

Example 3: Team System (from Football)

-- user.lua excerpt
team = 0  -- 0=spectator, 1=red, 2=blue

function change_team_ALL(sender_id, _team)
    team = _team

    if team == 0 then  -- Spectator
        if IS_LOCAL then
            set_camera_target("*ball")
        end
        delete_visuals()
        return
    end

    -- Create player visuals
    collision_name = set_collision({
        parent_name = name,
        shape = "circle",
        size = 16
    })

    if IS_LOCAL then
        set_camera_target(name)
    end

    nickname_label_name = set_label({
        parent_name = name,
        text = nickname,
        position = Vector2(-256, 16),
        size = Vector2(512, 16),
        horizontal_alignment = 1
    })

    image_name = set_image({
        parent_name = name,
        image_path = is_avatar_loaded and name or "",
        scale = Vector2(32, 32)
    })

    -- Apply team color
    local color = team == 1 and Color(1, 0, 0, 1) or Color(0, 0, 1, 1)
    set_shader({
        parent_name = name,
        image_name = image_name,
        shader_name = "circle",
        outline_color = color
    })

    reset_position()
end

function reset_position()
    if not IS_HOST then return end

    local spawn_area = team == 1 and "red_spawn_area" or "blue_spawn_area"
    local new_pos = get_random_position_in_polygon(spawn_area)

    change_instantly({
        entity_name = name,
        position = new_pos,
        linear_velocity = Vector2(0, 0),
        rotation = 0,
        angular_velocity = 0
    })
end

6. Best Practices

Important Limitations and Rules

Critical Rules:
  • Max Velocity: Entity velocity is capped at 600. Values above this are unnecessary.
  • Z-Index Range: All z_index values must be between -999 and 999.
  • User Data Types in Tables: Vector2 and Color types CANNOT be used as table keys - you will get errors. Use strings or numbers as keys instead.
  • Local Variables: Variables declared with local keyword cannot be accessed with get_value or set_value. Only global entity variables can be accessed this way.
  • Return Values: run_function and get_value cannot return multiple values directly. To return multiple values, wrap them in a table.
  • Top Variables Must Be Primitive: Variables declared at the top of the script (before any function, comment, or blank line) must be primitive types (numbers, strings, booleans). Special configuration variables like network_mode, singleton_name, area_radius, etc. are parsed before script execution.
-- BAD: Vector2 as table key
local my_table = {}
my_table[Vector2(10, 20)] = "value"  -- ERROR!

-- GOOD: String as table key
local my_table = {}
my_table["10,20"] = "value"

-- BAD: Returning multiple values
function get_position_and_health()
    return position.x, position.y, health  -- Only first value returned!
end

-- GOOD: Return table with multiple values
function get_position_and_health()
    return {x = position.x, y = position.y, health = health}
end

-- BAD: Local variable with get_value
local secret_value = 100
local val = get_value("", name, "secret_value")  -- Returns nil!

-- GOOD: Global variable with get_value
secret_value = 100
local val = get_value("", name, "secret_value")  -- Works!

Performance Optimization

-- BAD: Repeated get_value calls
function _process(delta, inputs)
    local target_pos = get_value("", target_name, "position")
    local target_health = get_value("", target_name, "health")
    local target_team = get_value("", target_name, "team")
    -- Expensive repeated lookups every frame!
end

-- GOOD: Cache values when they change
target_pos_cache = Vector2(0, 0)
target_health_cache = 100
target_team_cache = 1

function on_target_updated_ALL(sender_id, pos, health, team)
    target_pos_cache = pos
    target_health_cache = health
    target_team_cache = team
end

function _process(delta, inputs)
    -- Use cached values - much faster!
    local distance = (target_pos_cache - position).length()
end

-- BAD: Repeated network calls
for i = 1, 10 do
    run_network_function("user", "update_value_ALL", {i})
end

-- GOOD: Single batched call
local batch = {}
for i = 1, 10 do
    table.insert(batch, i)
end
run_network_function("user", "update_batch_ALL", {batch})

Entity Lifecycle

-- Proper cleanup on disconnect
function _on_user_disconnected(steam_id, nickname)
    if steam_id == name then
        -- Clean up all associated entities
        destroy("", hook_entity_name)
        destroy("", cursor_name)
        destroy_line(hook_line_name)
        stop_timer("shoot_timer"..name)
    end
end

Error Handling

-- Always validate entity existence
local target_pos = get_value("", target_name, "position")
if not target_pos then
    print("Warning: Target entity not found: " .. target_name)
    return
end

-- Check for nil values
local nearest = get_nearest_entity_by_tag(name, "enemy")
if nearest and nearest.name and nearest.name ~= "" then
    -- Safe to use nearest.name
end

Debugging

-- Use print for debugging (shows in console)
print("DEBUG: Player fired weapon at position:", position.x, position.y)

-- Use chat for in-game debugging
if IS_HOST then
    add_to_chat("[DEBUG] Score updated: " .. score, false)
end
Inspecting your card set: press F4 to open the debug console and type show_all_cards. A scrollable gallery opens showing every card face your mod has loaded, grouped by set: each card's front, any custom back, and the set's shared back, with the card's name plus its raw id and rendered resolution underneath. It works for every card set (load_cards_from_json, load_cards_from_data and load_cards_from_png) with no extra code in your mod, so it is the fastest way to eyeball a whole deck's artwork after a change.

7. Uploading To Steam Workshop

Once your mod is ready, you can share it with the community by uploading it to the Steam Workshop. The entire process is handled directly within the cenker's mod editor.

Note: To upload or update your mod, click the Submit button located in the top right corner of the editor interface.

Setting Up Description and Icon

The Workshop item automatically uses specific files from your mod directory:

Mapping description and icon

Your local files are mapped to the Workshop UI automatically.

Supported File Types

For safety, a mod may only contain these file types: .png, .ogg, .lua, .txt and .json. Anything else is refused, and the upload is stopped with a "Not Allowed By Whitelist" error listing the offending files. Remove them and try again.

Note: Renaming a file does not help โ€” the contents are checked as well, so a file named sound.ogg that is not really an OGG will still be rejected. The same check runs when other players download your mod, so an unsupported file makes the mod unloadable for everyone. Hidden folders such as .git are ignored and are safe to keep.

Categories and Genres

When you click Submit, you'll need to configure your mod's categorization:

Updating Your Mod: If you are updating an existing mod, you should select the same Category and Genre as before. Don't forget to include your Change Notes so users know what's new!
Configuring change notes and categories

The Upload Process

During the upload, the game will communicate with Steam servers. A progress window will appear.

Do Not Close: "cenker's mod" must remain open throughout the entire upload process. Closing the game will interrupt the transfer.
Upload in progress

Finalizing

Once successful, you'll receive a confirmation with your File ID. You can click "View on Workshop" to see your live project and manage it through the Steam interface.

Upload successful

8. Dedicated & Master Servers

Experimental: dedicated servers and custom master servers are new and may not work as expected yet. In the game they are marked (experimental) - hover over them for a reminder. If something goes wrong, please report it on the game's Steam Community page, with what you did and the server's console output if you have it.

cenker's mod can be hosted in three ways. They all run the same game code, so a mod works in each of them without changes, and you choose what fits your community: a quick game with friends, a public server that is always on, or a network of servers that does not need Steam at all.

1. A player hosts (Steam)The classic way.Steam lobby + Steam P2P.The host also plays.Listed in the room list. 2. A player hosts (master)Same game, no Steam.Listed on your own master.NAT punching, relay as backup.The host also plays. 3. Dedicated serverHeadless, no window.No player of its own.Runs on a PC or a VPS,as many as you like.

8.1 Dedicated servers

A dedicated server hosts one mod for as long as it runs. It has no window, no character and nobody at the keyboard, and it does not need the Steam client - so it fits on a cheap Linux VPS or a spare Windows PC. It is still the authority of the game (IS_HOST is true there), exactly like a player who hosts, but it never counts as a player: it takes no team, no seat and no vote.

A dedicated server starting from start_server.sh: it loads the mod, opens its UDP port and lists itself on the master server.
A dedicated server starting from start_server.sh: it loads the mod, opens its UDP port and lists itself on the master server.
Dedicated servermods/Football + server.json Steamserver browser Playerroom list / Steam browser registers (GodotSteam Server) lists servers joins by address (UDP 27015), encrypted mod files, world, chat, voice

Setting one up

  1. Get the server build (the Dedicated Server tool, or the Dedicated Server folder of the game's repository).
  2. Put the mod you want to host (and any addons) into its mods/ folder.
  3. Copy server.example.json to server.json and edit it.
  4. Open the game port in your firewall/router (UDP 27015 by default; also 27016 when listed on Steam).
  5. Start start_server.sh (Linux) or start_server.bat (Windows).
{
  "name": "Friday Football",
  "mod": "Football",
  "addons": ["Moderation Panel"],
  "max_players": 16,
  "game_port": 27015,
  "master": "steam",
  "steam_only": false,
  "owners": ["76561198000000000"]
}
OptionWhat it is for
mod, addons, mapWhat to host: folder names inside mods/, merged in order, and the map (the first one when empty).
name, genre, countryHow the server looks in the room list.
max_players, game_port, query_portSize and network ports. Use a different port for every server on one machine.
master"steam" to be listed on Steam, or "address:port" of a custom master server.
steam_onlyOnly accept players signed in through Steam. Can also be switched while running.
ownersPlayer ids (as text) with admin rights.
gsltOptional Steam token that keeps the server's Steam identity across restarts.
data_dirWhere the server keeps its world, bans, moderators and its identity key.
Saves survive restarts. The mod is copied into data/world on every start, so updates arrive, while anything the mod saved there itself (a MineBlockLand world, high scores) is kept.

The console

Type into the server window: status, say, kick, ban, unban, mod add|remove|list (moderators), steam_only on|off, any mod command such as /start, and quit.

Server "Friday Football" is running: mod Football, map 44x32 FootballMap, UDP port 27710. Type help for commands.
Listed on the master server.
unnamed joined (259657334682074).
status
Friday Football | mod Football | map 44x32 FootballMap | players 1/16 | Steam only: off
  259657334682074  unnamed  player

8.2 Custom master servers - hosting without Steam

A master server is a small separate program (the Master Server folder) that lists servers and helps players reach them. Run it on any machine with a public address and share its address:port. In the game, choose Custom master server in the hosting menu or the room list and type that address; Steam stays the default for everyone else.

The master server running: its key fingerprint, a dedicated server registering and the status and list console commands.
The master server running: its key fingerprint, a dedicated server registering and the status and list console commands.
Hosting menu with <em>Custom master server</em> selected: the address field, the game port and the Steam-only option appear.
Hosting menu with Custom master server selected: the address field, the game port and the Steam-only option appear.
Room list reading a custom master server: the dedicated server is listed in the same rows as lobbies.
Room list reading a custom master server: the dedicated server is listed in the same rows as lobbies.
Hostdedicated or a player Master serveryour own, Steam-freeUDP 27100 + 27101 PlayerCustom master selected 1. register (+ STUN) 2. list, connect 3. "punch" 3. "punch" 4. direct connection through NAT 5. if punching fails: relayed by the master, still end-to-end encrypted

8.3 Playing without Steam

On dedicated and custom-master servers a player does not need Steam. Their identity is a key created on their computer; their name and picture are set in Settings → General (a generated pattern is used when no picture is chosen). Copy my player ID there gives the id a server owner puts in owners: the Steam ID, or the 15-digit local user id without Steam. A server that wants Steam accounts only turns on steam_only. Voice chat currently needs Steam.

Settings → General: name, picture and player ID used on servers joined without Steam.
Settings → General: name, picture and player ID used on servers joined without Steam.

Additional Resources

For complete API documentation, refer to cenkers_mod_stub.lua in your mod directory. This file contains detailed type annotations and parameter descriptions for all available functions.

Study the included example mods (Football, Hook Up, Campfire Survivors) to see these concepts in action!

For complete documentation, refer to cenkers_mod_stub.lua in your mod directory.