Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Level Objects

Objects are created by creating a folder in level/objects. As each folder corresponds to an object that can be referenced from within Tiled, the name of the folder == the object name as used in Tiled.

From there, an Object must have a Lua file titled main.lua within it. This file is otherwise self-explanatory (see below for the expected functions). It can have other Lua files which are then referenced as modules via Lua’s require function.

If a object is especially big and/or contains lots of variables that are referenced across fiels (such as the player object) you may want to put important global variables in a “vars.lua” file that gets referenced across multiple files.

Each object has its own confined Lua state, with its own scope. All of them have an Object global which is used to access things that the engine expects them to have (or to interact with the engine in general), i.e. Object.position and Object.size. It can communicate (somewhat limitingly, see the relevant docs) with objects it collides with via Object:get and Object:set.

Objects are also responsible for loading textures with Renderer:load_texture and then drawing them via Renderer:draw_texture_opt (Or draw_texture, but as of writing this, that one is broken).

When in doubt, see the player object’s main.lua, which has everything wrapped up neatly and can thus serve as good example code.

Expected Functions

There are three functions expected to be within an object’s Lua scope. These should idomatically be put in main.lua, but they can be placed in other files (however I’ve only ever done it in main.lua and I don’t know if placing them in other modules messes with the game’s ability to see them; it shouldn’t but if your functions aren’t being loaded check this).

init function

Called upon the object’s creation.

--- @param win Window
--- @param renderer Renderer
function init(win, renderer)
-- ...
end

tick function

Called every tick for every object in the level.

---@param win Window
-- tick function
function tick(win)
-- ...
end

draw function

Called for every object on screen. This is where you draw a texture at your object’s position.

--- @param renderer Renderer
--- @param cameraPos Vec2
function draw(renderer, cameraPos)
-- ...
end

Notice that camera position is passed in. If you want to draw something at your object’s current position, you need to do something like:

-- textureOptions being a TextureOptions in this case. 
textureOptions.dest.x = (Object.position.x - cameraPos.x)
textureOptions.dest.y = (Object.position.y - cameraPos.y)

Having this be done manually is useful so that there can be HUD objects or objects that mess with the entire screen for any reason.

on_collide function

Called upon the object colliding with another object.

---@param obj Object
function on_collide(obj)
-- ...
end