Log inGet started
World

Tool Time: Hold a Tool and Work the Tile in Front Kit

Branchmain
Branchesmain
Commitc37d931243

README.md

toolUseKit

Hold a tool and use it on the tile in front of the player. A hoe, a watering can, a seed pouch, an axe, a pickaxe, a scythe, a hammer, or any tool you define as data. Tools come in upgrade tiers (Basic, Copper, Steel, Gold, Iridium) that cover a bigger area, a use can be held to charge up to the tier's biggest pattern (like Stardew Valley), every use costs energy, and the game reacts through hooks. The kit knows nothing about crops, rocks or trees, so it fits farming games, mining games, gardening, building, cleaning or anything played on a grid.

Version 1.0.4 (Tools.VERSION). This README, package.yaml and Tools.VERSION move together.

What a world gets from installing it:

  • Seven tools as data. tools/*.data, bound to the toolDef contract, and Tools.defineTool for your own. Each tool has an id, a name, a short label, an icon, a kind, an energy cost per tier and five tiers, each with a name, an area pattern, a charge time and colours per style.
  • 175 held-tool variants. 7 kinds x 5 tiers x 5 styles (cartoon, pixel, painted, realistic, scifi). Every tier looks different: head colour and metal, grip wrap, a metal collar from Steel, a gem from Gold, a glow at Iridium. Walk past all of them in the gallery scene.
  • Hold to charge. Holding use climbs a ladder of patterns (single, line of 3, line of 5, 3x3, 5x5 or your own offsets) up to the tier's biggest.
  • Energy. A meter with a max, optional regeneration, a low warning, an exhausted event and a refund when nothing was hit.
  • Six target highlights that mark every cell the next use will hit: softOutline, pixelSquare, paintedRing, hologram, tileTint, corners.
  • Swings with juice: the hoe chops down, the can tilts and pours, the seed pouch flicks seeds out, the axe swings sideways, the pickaxe goes overhead, the scythe sweeps, the hammer knocks twice; dust, splashes, seeds, wood chips, splinters, stone chips with sparks, grass bits, and ten sounds made for the kit.
  • Six energy meter looks: bar, leaf, sun, pixel, hologram, none. The meter rides with the tool strip, so one setting moves both.
  • Controls that do not clash: E (interact), the d-pad and the gamepad west button (hotbar and interact) and, by default, the number keys stay free for the game and its other kits.
  • A phone HUD: safe-area aware, 44 point touch targets, short labels and wrapping on narrow screens, clear of the on-screen touch buttons, in landscape and portrait.
  • Multiplayer from the start. Every player sees everyone's held tool and swing, late joiners included. Each player's tools, tiers and energy are saved and come back when they rejoin.
  • A test suite covering areas, energy, the new kinds, bindings and the phone layout.

Hard dependencies: none. It uses only engine built-ins (input maps, runtime_data, the UI and multiplayer surfaces), so it installs beside any release of controlsKit, saveKit, inventoryKit, friendshipKit or barsKit.

Quick start (5 minutes)

  1. Install toolUseKit into your world.
  2. Make sure your scene has a player (a fresh world's scene does).
  3. Add a component to any entity in the scene, or put this in a scene entrypoint, so it runs on every peer:
local Tools = require("~toolUseKit.api")

function awake()
	Tools.setup({
		cellSize = 1,
		origin = { 0, 0, 0 },
		style = "cartoon",
		energy = { max = 270 },
		hudPosition = "bottom-center",
		numberKeys = false, -- true: 1-7 pick a tool (leave false beside an inventory hotbar)
		startTools = { { id = "hoe", tier = 1 }, { id = "seedPouch", tier = 1 }, { id = "hammer", tier = 1 } },
	})

	Tools.onUse("hoe", function(ctx)
		for _, cell in ctx.cells do
			print("tilled", cell.x, cell.z, "at", cell.world[1], cell.world[3])
		end
		return true -- return false when nothing happened: the energy comes back
	end)

	-- the seed pouch: the game decides what is sown, on the cells the kit hands it
	Tools.onUse("seedPouch", function(ctx)
		local sown = 0
		for _, cell in ctx.cells do
			if MyFarm.isTilled(cell.x, cell.z) and MyBag.take(MyBag.selectedSeed()) then
				MyFarm.plant(cell.x, cell.z, MyBag.selectedSeed())
				sown += 1
			end
		end
		return sown > 0
	end)

	-- the hammer: break or repair what stands on the cells
	Tools.onUse("hammer", function(ctx)
		local n = 0
		for _, cell in ctx.cells do
			local thing = MyBuild.at(cell.x, cell.z)
			if thing then
				if thing.broken then thing:repair() else thing:damage(ctx.tier + ctx.chargeLevel) end
				n += 1
			end
		end
		return n > 0
	end)
end

(MyFarm, MyBag and MyBuild stand for your game's own systems.)

  1. Press play. The player holds a hoe, a highlight marks the cell in front, left click (or C, the right trigger, or the USE button on a phone) uses it.

The seven tools

idkinddoesarea by tier (Basic, Copper, Steel, Gold, Iridium)energy per use
hoehoetills the groundsingle, line3, line5, square3, square52
wateringCanwateringCanwaters the groundsingle, line3, line5, square3, square52
seedPouchseedPouchsows; the game picks the seed in its handlersingle, line3, line5, square3, square51
axeaxechops woodsingle, single, line3, line3, line54, 3, 3, 2, 2
pickaxepickaxebreaks rocksingle, single, line3, line3, square34, 3, 3, 2, 2
scythescythecuts grass and weedswide3, wide3, arc5, wide5, square31, 1, 1, 1, 0
hammerhammerbreaks or repairs placed thingssingle, single, line3, line3, square33, 3, 2, 2, 2

A tap hits the first pattern of the tool's ladder; holding climbs one pattern per charge step up to the tier's biggest. A charged use costs the tier's cost times 1 + level x chargeCost.

Variant counts: 7 kinds x 5 tiers x 5 styles = 175 held models, plus a generic kind for tools of your own (any kind the kit does not know builds as generic, or set model to hold your own mesh or bundle).

Controls

actionkeyboard and mousegamepadtouch
use (hold to charge)left click or Cright triggerUSE button
next toolF or mouse wheel downright bumpertap the tool strip
previous toolQ or mouse wheel upleft bumpertap the tool strip
pick slot 1-71-7, only with numberKeys = truenonetap the tool strip

Left free on purpose: E and the gamepad west face button (the engine's interact), the d-pad (games use it to pick hotbar slots), Tab, G, I (inventoryKit), R, O (friendshipKit) and, unless you turn numberKeys on, 1-9 (an inventory hotbar). The main controls are controls.inputMap; the number keys are a separate numberKeys.inputMap the kit only activates when the option is on, so the keys are never bound while it is off. On a phone the USE button sits first in the touch button column, so a small screen never folds it into the "..." button.

The API

local Tools = require("~toolUseKit.api"). Everything acts on the local player; uses run on the using player's own machine.

Setup and looks

functionwhat it does
Tools.setup(opts)configure; call on every peer. Calling again changes only what you pass. Returns the settings.
Tools.settings()the settings in use
Tools.style() / Tools.setStyle(name)the held-model style, live
Tools.highlight() / Tools.setHighlight(look)the target highlight (nil: the style's own)
Tools.energyLook() / Tools.setEnergyLook(look)the energy meter look (nil: the style's own)
Tools.controlMaps()the input maps the kit activates with the settings in use (controls, plus numberKeys when on)
Tools.hudLayout(W?, H?, safe?)where the strip and meter go on a screen (defaults: the current screen and safe area)
Tools.catalogue()styles, highlights, energy looks, patterns, tools with tiers, swings, sounds, events, options, hud positions
Tools.stats()state for tests and debugging

setup options:

optiondefaultmeaning
cellSize1grid cell size in metres
origin{0,0,0}where cell 0,0 starts; y is the height the highlight sits at
style"cartoon"cartoon, pixel, painted, realistic, scifi (also cozy, voxel, sci-fi...)
highlightstyle's ownone of the highlight looks
highlightHeight0.03metres above origin.y
energyLookstyle's ownone of the energy looks
energy{ max = 270, regenPerSecond = 0, exhaustedSlowdown = true, lowFraction = 0.2 }the meter (start sets the first value). exhaustedSlowdown is reserved: 1.0.x does not slow the body itself, so slow your controller from Tools.on("exhausted", fn)
startToolsall seven at tier 1{ {id, tier} } a new player starts with, in strip order
equipfirst start tooltool held at the start
reach1how many cells in front the target is
facing"cardinal""cardinal" (4 ways) or "eight"
spendOnMissfalsea use every handler said missed still costs energy
allowTiredUsefalseallow a use with too little energy (energy goes to 0)
hud, controls, soundtruethe kit's tool strip and meter, its controls, its sounds
hudPosition"bottom-center"where the tool strip and its energy meter sit together: "bottom-center", "top-left", "bottom-left", "top-center". Pick the one other kits leave free
numberKeysfalsetrue binds 1-7 to the strip slots; false leaves the number keys to an inventory hotbar (the slots have no keyboard keys)
volume0.8sound volume
persisttruesave tools, tiers and energy per player
saveKey"default"keep separate saves per game mode
maxTiernilcap every tool's tier

Tools as data

functionwhat it does
Tools.defineTool(def)add or replace a tool from code; returns the normalised def
Tools.definePattern(name, offsets)name a pattern: { {side, forward} }, forward 0 is the target cell
Tools.pattern(name)the offsets of a pattern
Tools.tool(id) / Tools.tools()a tool definition / every tool definition

A tool def: { id, name, short, icon, kind, description, swing, useTime, ladder, energyCost (number or one per tier), chargeCost, model, modelScale, tiers }. A tier: { name, pattern, patterns, offsets, chargeTime, color, accent, gem, glow, tints = { cartoon = "#hex", ... } }. kind picks the model and swing (hoe, wateringCan, seedPouch, axe, pickaxe, scythe, hammer, generic); swing overrides the animation (chop, overhead, side, sweep, pour, sow, knock); model names a mesh or bundle to hold instead of the built model; short is the strip label on narrow screens.

A .data asset bound to the toolDef contract anywhere in your world is loaded as a tool too (see toolDef.dataType/README.md).

Owning, tiers and holding

functionwhat it does
Tools.give(toolId, tier?)give a tool (keeps a higher tier the player has)
Tools.take(toolId)take it away
Tools.has(toolId)whether the player has it
Tools.getTier(toolId) / Tools.setTier(toolId, tier)read / set a tier (fires tierChanged)
Tools.upgrade(toolId)one tier up
Tools.list()the player's tools in strip order: { id, tier, tierName, name, icon, kind, def, equipped }
Tools.equip(toolId) / Tools.unequip() / Tools.equipped()hold, put away, what is held
Tools.cycle(dir) / Tools.equipSlot(n)next or previous tool / the n-th tool
Tools.players()what every player in the room holds: { peer, toolId, tier, style }

Using

functionwhat it does
Tools.onUse(kindOrToolId, fn)react to uses of a kind, a tool id or "*"; returns an unsubscribe function
Tools.use(level?, cell?, facing?)use the held tool now from code (AI, tutorials, tests)
Tools.setTargetResolver(fn)replace how the target cell is found (gridKit, your own plots); nil restores the grid
Tools.target(){ cell, facing, position, forward }
Tools.previewCells(level?)the cells the next use would hit
Tools.charge(){ active, level, maxLevel, fraction, time }
Tools.costOf(toolId, tier?, level?)the energy a use costs
Tools.worldToCell(p) / Tools.cellToWorld(x, z)grid conversions
Tools.lastUse() / Tools.useCount()the last ctx / how many uses on this machine

The ctx a handler gets: player (the body), playerId (peer id), userId, tool (the def), toolId, kind, tier, tierName, chargeLevel (0 is a tap), cells ({ { x, z, world = {x,y,z} } }, every cell the use covers), cellCount, facing ({ x, z }), origin (the target cell { x, z }) and energySpent. Return false to say nothing happened there; when every handler says so the kit fires miss and, unless spendOnMiss is on, gives the energy back. After handlers ran, ctx.hit and ctx.refunded are set. The seed pouch and the hammer use this same flow: the kit hands over the cells, the game decides what is sown, broken or repaired.

A resolver gets { player, position, forward, facing, reach, cellSize, origin, defaultCell } and returns a cell { x, z } (and optionally a facing).

Energy

Tools.energy(), Tools.maxEnergy(), Tools.setEnergy(n), Tools.addEnergy(n), Tools.restoreEnergy(), Tools.setMaxEnergy(n), Tools.isExhausted().

Events

Tools.on(event, fn) returns an unsubscribe function.

eventarguments
usectx
miss{ reason = "noTool" | "tired" | "nothing", toolId, ctx }
equipnew id (nil when put away), old id
unequipold id
tierChangedtoolId, new tier, old tier
givetoolId, tier
energyChangedenergy, old, max, why
lowEnergyenergy, max
exhaustedmax
chargelevel, maxLevel
readythe player's tool list once their save loaded

Saving

Tools.save() writes now (it also saves a second after any change), Tools.resetProgress() forgets the player's tools, Tools.isReady() says whether the save has loaded. Saves live in each player's own runtime_data.player(id) store under toolUseKit/<saveKey>, the same store saveKit uses, so they survive leaving and rejoining. A player saved before 1.0.4 keeps their own tools; give them the seed pouch and hammer with Tools.give when your game hands them out.

Phones

The strip and the energy meter form one group, placed at hudPosition inside ui.safeArea(): a screen's frame starts at the safe area's top-left corner, so the kit lays out in safe-area space and never runs under a notch, a status bar or a gesture bar. On a narrow screen (a phone in landscape, about 693x390 points, or portrait, about 390x844) slots shrink to 52x46 points (never under 44), labels shorten (Hoe, Can, Seeds, Axe, Pick, Scythe, Hammer) and the strip wraps into rows when it must. With a touch screen the group keeps clear of the on-screen buttons: it fits between them when there is room and otherwise steps up above them (top anchors step down). The placement is Hud.layout(W, H, safe, opts), a pure function the tests run at both phone shapes.

The gallery scene

gallery.scene is a walkable hall: five booths, one per style, each with the seven kinds in labelled rows and the five tiers in labelled columns, all 175 variants. A panel shows every energy meter look (it folds away on phones), and the player holds all seven tools to try them. Open it with layers.load("toolUseKit.gallery") (or the Scenes panel) and press play.

Tests

tests/toolUseKit.testSuite checks the area per tier for every kind, the energy cost and the refund on a miss, the seed pouch and hammer (models in every style and tier, sounds, the ctx cells), that no binding uses KeyE, that number keys are bound only when numberKeys is true, that nothing is on the d-pad or the west button, and that the HUD stays inside the safe area with 44 point targets at 693x390 and 390x844 in every position. Run it in edit mode:

return tools.use("tests", "run", { suite = "toolUseKit" })

or from the shell, zero tests run --suite toolUseKit.

Every style list

  • Styles: cartoon (cozy, chunky, outlined), pixel (voxel cubes), painted (pastel, brushy), realistic (slim wood, brushed metal), scifi (dark alloy, glowing edges).
  • Highlights: softOutline, pixelSquare, paintedRing, hologram, tileTint, corners.
  • Energy looks: bar, leaf, sun, pixel, hologram, none.
  • HUD positions: bottom-center, top-left, bottom-left, top-center.
  • Patterns: single, line3, line5, wide3, wide5, arc5, cross, square3, square5, plus your own.
  • Swings: chop, overhead, side, sweep, pour, sow, knock.
  • Sounds: dig, chop, clink, pour, swish, whoosh, equip, charge, sow, hammer (Tools.fx.sound(name, at)).

Working beside other kits

  • inventoryKit: keep numberKeys = false (the default) so its hotbar keeps 1-9; it uses Tab, G and I, which the kit leaves alone. Call Tools.give(id, tier) when a tool item lands in the bag and Tools.take(id) when it leaves. A seed pouch handler can take the selected seed from the bag.
  • friendshipKit: uses R and O, left alone; if its Friends button shares your corner, move the strip with hudPosition.
  • saveKit: both keep per-player data in runtime_data.player(id); they do not collide (toolUseKit/... paths).
  • barsKit: set energyLook = "none" and feed a barsKit bar from Tools.on("energyChanged", ...).
  • gridKit or your own plots: Tools.setTargetResolver(fn).
  • controlsKit: set controls = false and call Tools.use / Tools.cycle from your own scheme, or keep the kit's controls (its map is in the player group and composes with walking).

Parts

partwhat it is
api.modulethe front door
defs.modulepatterns, tiers and the tool registry
looks.modulestyles, highlight looks, energy looks, palettes
models.modulethe procedural held models
fx.moduleswing poses, particles, sounds
highlight.modulethe target markers
hud.modulethe tool strip and energy meter tree, and the pure layout
ToolUseHost.componentruns the kit for the local player (spawned by itself)
ToolHolder.componenta player's synced held tool (spawned by itself)
controls.inputMapuse and switch on keyboard and mouse, gamepad and touch
numberKeys.inputMap1-7 slot keys, live only with numberKeys = true
toolDef.dataType, tools/*.datathe tool contract and the seven tools
sounds/the kit's ten sounds
gallery.sceneevery variant side by side, every meter look
tests/toolUseKit.testSuitethe regression tests
guides/how to add tools, and a mining and gardening example

Guides: How to add tools like a hoe, axe and watering can to my game (guides/add-tools-hoe-axe-watering-can.guide) and Example: make a mining and gardening game where tools upgrade to hit a bigger area (guides/mining-gardening-upgrade-example.guide).

Version history

  • 1.0.4: two new tools, the seed pouch (sows on the cells in front, the game picks the seed through onUse) and the hammer (breaks or repairs placed things), each with models in all 5 styles and 5 tiers, a swing, particles, a sound and energy costs: 175 variants. Controls no longer clash: next tool moved from E to F (E is the engine's interact), the number keys moved to a separate map behind the new numberKeys option (off by default), the gamepad uses the bumpers and right trigger only. The HUD is safe-area aware with the new hudPosition option, keeps the energy meter attached to the strip, fits phones in landscape and portrait with 44 point targets and keeps clear of the touch buttons; the USE touch button takes the first slot. ctx.cellCount, Tools.controlMaps(), Tools.hudLayout(), a gallery scene and a test suite.
  • 1.0.3 and earlier: five tools, five tiers, five styles, energy, highlights, multiplayer and saving.